RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
freebsd fixes
oxydizerb31837bbdccb
diff --git a/AGENTS.md b/AGENTS.mdindex 46e3834..b10ce62 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -266,6 +266,12 @@ 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.+* **System paths come from `install_paths`:** `sysconfdir` (`/etc`; `/usr/local/etc`+ targeting FreeBSD) for our own configuration and `rundir` for run state, never a+ literal `/etc/rediwm` or `/run/...` (C gets `-DREDIWM_SYSCONFDIR`). Third-party+ locations (`/etc/xdg`, `/etc/login.defs`) stay literal.+* **Other processes** (list, stat, parent, uids, exe) are read through+ `system_monitor/proc.zig`; only its Linux backend touches `/proc`.* **OS calls go through `src/platform/`**: use it, not `pidfd_*`, `inotify_*`,`SO_PEERCRED`, `prctl`, `eventfd` flags, `renameat2`, `statx` or `/proc/self/exe` (C and C++: its`child.h`, `self_exe.h`, `peer.h`, `process.h`). Elsewhere call libc ordiff --git a/build.zig b/build.zigindex 4e4461f..a7bfac6 100644--- a/build.zig+++ b/build.zig@@ -21,8 +21,8 @@ const localizedData = support.localizedData;const addCatalogInputs = support.addCatalogInputs;pub fn build(b: *std.Build) void {- const layout = @import("build/install_paths.zig").Layout.init(b);const target = b.standardTargetOptions(.{});+ const layout = @import("build/install_paths.zig").Layout.init(b, target.result.os.tag);const optimize = b.standardOptimizeOption(.{});// On FreeBSD the self-hosted backend's executables lack crt1's `environ`, which libc.so.7 needs// (a Debug rediwm-cursorgen died at startup, its ReleaseSafe build did not), so LLVM is the default there.@@ -188,7 +188,7 @@ pub fn build(b: *std.Build) void {addBassDsp(b, target);compositor.root_module.linkSystemLibrary("pam", .{});compositor.root_module.linkSystemLibrary("xcb", .{});- compositor.root_module.addCSourceFile(.{ .file = b.path("src/session/auth.c"), .flags = &.{"-std=c11"} });+ compositor.root_module.addCSourceFile(.{ .file = b.path("src/session/auth.c"), .flags = &.{ "-std=c11", b.fmt("-DREDIWM_SYSCONFDIR=\"{s}\"", .{layout.sysconfdir}) } });compositor.root_module.addCSourceFile(.{ .file = b.path("src/polkit/native.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });addGlass(b, compositor.root_module, damage_audit);if (frame_trace) compositor.root_module.addCMacro("REDIWM_FRAME_TRACE", "1");diff --git a/build/install_paths.zig b/build/install_paths.zigindex a506d71..a22b31b 100644--- a/build/install_paths.zig+++ b/build/install_paths.zig@@ -1,39 +1,59 @@//! Runtime paths are independent of Zig's output/staging directory.const std = @import("std");+/// Where RediWM's own system configuration lives (`rediwm/dm.conf`, the PAM+/// policy, CUPS's client.conf): `/etc`, but `/usr/local/etc` for ports.+pub fn defaultSysconfdir(os: std.Target.Os.Tag) []const u8 {+ return if (os == .freebsd) "/usr/local/etc" else "/etc";+}++/// Runtime state of system services (the display manager's marker directory).+pub fn defaultRundir(os: std.Target.Os.Tag) []const u8 {+ return if (os == .freebsd) "/var/run" else "/run";+}+pub const Layout = struct {prefix: []const u8,+ sysconfdir: []const u8,options: *std.Build.Module,- pub fn init(b: *std.Build) Layout {+ pub fn init(b: *std.Build, os: std.Target.Os.Tag) Layout {const raw = b.option([]const u8, "install-prefix", "Runtime installation prefix (default /usr/local; --prefix only selects build output)") orelse "/usr/local";- // These paths appear in shell commands, desktop files, XML and systemd- // units. Reject metacharacters rather than giving each format different- // escaping semantics. Never allow a staging path to be inferred here.- if (raw.len == 0 or raw[0] != '/') @panic("install-prefix must be absolute");- for (raw) |ch| {- if (!std.ascii.isAlphanumeric(ch) and std.mem.indexOfScalar(u8, "/_-+.", ch) == null)- @panic("install-prefix supports only letters, digits, /, _, -, + and .");- }- var parts = std.mem.splitScalar(u8, raw, '/');- while (parts.next()) |part| {- if (std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) @panic("install-prefix must not contain . or .. components");- }- const normalized = std.fs.path.resolve(b.allocator, &.{raw}) catch @panic("out of memory");+ const normalized = normalize(b, "install-prefix", raw);const prefix = std.mem.trimEnd(u8, normalized, "/");+ const sysconfdir = std.mem.trimEnd(u8, normalize(b, "sysconfdir", b.option([]const u8, "sysconfdir", b.fmt("System configuration directory (default {s}; {s} when targeting FreeBSD)", .{ defaultSysconfdir(.linux), defaultSysconfdir(.freebsd) })) orelse defaultSysconfdir(os)), "/");+ const rundir = std.mem.trimEnd(u8, normalize(b, "rundir", b.option([]const u8, "rundir", b.fmt("Runtime state directory (default {s}; {s} when targeting FreeBSD)", .{ defaultRundir(.linux), defaultRundir(.freebsd) })) orelse defaultRundir(os)), "/");const options = b.addOptions();options.addOption(bool, "git_integration", b.option(bool, "git-integration", "Enable Files Git integration") orelse true);options.addOption([]const u8, "prefix", prefix);+ options.addOption([]const u8, "sysconfdir", sysconfdir);+ options.addOption([]const u8, "rundir", rundir);options.addOption([]const u8, "bin", b.fmt("{s}/bin", .{prefix}));options.addOption([]const u8, "data", b.fmt("{s}/share", .{prefix}));options.addOption([]const u8, "search_path", b.fmt("{s}/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin", .{prefix}));options.addOption([]const u8, "data_dirs", b.fmt("{s}/share:/usr/local/share:/usr/share", .{prefix}));const manifest = b.addWriteFiles().add("install-prefix", b.fmt("{s}\n", .{normalized}));b.getInstallStep().dependOn(&b.addInstallFileWithDir(manifest, .prefix, "install-prefix").step);- return .{ .prefix = prefix, .options = options.createModule() };+ return .{ .prefix = prefix, .sysconfdir = sysconfdir, .options = options.createModule() };}};+/// These paths appear in shell commands, desktop files, XML, systemd units and+/// C string literals. Reject metacharacters rather than giving each format+/// different escaping semantics. Never allow a staging path to be inferred here.+fn normalize(b: *std.Build, name: []const u8, raw: []const u8) []const u8 {+ if (raw.len == 0 or raw[0] != '/') std.debug.panic("{s} must be absolute", .{name});+ for (raw) |ch| {+ if (!std.ascii.isAlphanumeric(ch) and std.mem.indexOfScalar(u8, "/_-+.", ch) == null)+ std.debug.panic("{s} supports only letters, digits, /, _, -, + and .", .{name});+ }+ var parts = std.mem.splitScalar(u8, raw, '/');+ while (parts.next()) |part| {+ if (std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) std.debug.panic("{s} must not contain . or .. components", .{name});+ }+ return std.fs.path.resolve(b.allocator, &.{raw}) catch @panic("out of memory");+}+pub fn configure(b: *std.Build, path: []const u8, prefix: []const u8) std.Build.LazyPath {b.dependOnFileContents(b.path(path));var dir = b.root.openDir(b.graph.io, ".", .{}) catch @panic("cannot open source directory");diff --git a/build/session.zig b/build/session.zigindex 6ffaaca..2490df9 100644--- a/build/session.zig+++ b/build/session.zig@@ -97,6 +97,7 @@ pub fn add(ctx: Context) Session {.use_lld = use_llvm,});accounts_helper.root_module.addImport("c", ctx.c.libc);+ accounts_helper.root_module.addImport("install_paths", ctx.layout.options);accounts_helper.root_module.addImport("wayland_sessions", ws_mod);accounts_helper.root_module.addImport("accounts_validation", b.createModule(.{.root_source_file = b.path("src/accounts/validation.zig"),diff --git a/build/tests.zig b/build/tests.zigindex 5cf085a..2ef0710 100644--- a/build/tests.zig+++ b/build/tests.zig@@ -138,6 +138,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {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("install_paths", ctx.layout.options);printing_tests.root_module.addImport("wayland", wayland);printing_tests.root_module.linkSystemLibrary("wayland-server", .{});printing_tests.root_module.linkSystemLibrary("cups", .{});diff --git a/docs/installation.md b/docs/installation.mdindex a3e8c4c..90e0230 100644--- a/docs/installation.md+++ b/docs/installation.md@@ -27,6 +27,14 @@ prefixes are absolute paths containing letters, digits, `/`, `_`, `-`, `+` and`.` (no `.` or `..` components). Prebuilt releases retain their recorded prefixand cannot be relocated by the installer.+`-Dsysconfdir` (default `/etc`, `/usr/local/etc` when targeting FreeBSD) is where+RediWM looks for its own system configuration: `rediwm/dm.conf`,+`rediwm/greeter.toml`, the `pam.d/rediwm` lock-screen policy and CUPS's+`cups/client.conf`. `-Drundir` (default `/run`, `/var/run` on FreeBSD) holds the+display manager's marker directory. Both follow the prefix's character rules.+The installers, units and tmpfiles still write `/etc` and `/run` (FreeBSD+packaging is phase 4 of [docs/plans/freebsd.md](plans/freebsd.md)).+System integration remains in `/etc`, `/usr/lib/{systemd/system,sysusers.d,tmpfiles.d}`and `/usr/share/{wayland-sessions,polkit-1/actions,xdg-desktop-portal/portals}`,under `DESTDIR` when staging. Runtime discovery of sibling executables and assetsdiff --git a/docs/plans/freebsd.md b/docs/plans/freebsd.mdindex c384cee..2116a7b 100644--- a/docs/plans/freebsd.md+++ b/docs/plans/freebsd.md@@ -1,12 +1,12 @@# FreeBSD support plan-Status: draft, 2026-11-05. The Linux-side preparation (P.1–P.4, P.7–P.10) is-done, P.5 and P.6 are open. The FreeBSD parts of `platform` are written and+Status: draft, 2026-11-05. The Linux-side preparation (P.1–P.4, P.6–P.10) is+done; P.5 and the P.9 review are open. The FreeBSD parts of `platform` are written andthe whole tree cross-compiles for `x86_64-freebsd` (Debug, ReleaseSafe, tests;see Validation). The third outside build (fa55c2a, FreeBSD 15.1 VM without a DRMrender device) builds Debug and ReleaseSafe and passes the platform tests, butthe compositor stops at renderer initialisation, so only unit tests have run.-Decisions D1–D6 are open.+Decisions D1–D5 are made (see Decisions); D6 waits for phase 2.Goal: 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@@ -55,10 +55,17 @@ a gdk-pixbuf port without the PNM loader; the test now skips there).The third run failed in five places, all tests: the system monitor's `/proc`readers (no procfs; they skip until P.6), the battery event test (raw Linuxsyscalls; now libc), the polkit helper's backpressure test (its fill loop-stopped at 64 KiB; longer now, unverified on FreeBSD), the editor view tests-(row height 5 px; probably no monospace font in the VM, unchecked) and Files-collation (`de_DE` and `ru_RU` sort `Élan` and `Ёж` before `Apfel`; open, it-would misorder Files listings).+stopped at 64 KiB; longer now), the editor view tests (the VM had no monospace+font; they pass with DejaVu installed, so a FreeBSD test host needs a font+package) and Files collation, the only one still failing at dcbaec1. A probe showed+that `strxfrm_l` and `strcoll_l` agree on FreeBSD, so Files' frozen keys are+sound; its libc tables are what differ from glibc's: `de_DE.UTF-8` is a link+to `en_US.UTF-8`, which sorts `Élan` before `Apfel` and gives Cyrillic names+no usable primary weights (`Яблоко` before `Ель`), and `ru_RU.UTF-8` puts+Cyrillic first with `Ёж` before `Еж`. Files therefore orders names as `ls`+does there. The two glibc-order tests skip off Linux (they also skip on a Linux+machine without those locales, as here); an own collation would be a separate+project (D7).### Interfaces still to port@@ -74,7 +81,7 @@ would misorder Files listings).| `/proc/self/exe` (`platform.exe`, `self_exe.h`) | Zig sites, `bass.c`, torrent helper, dm re-exec | `KERN_PROC_PATHNAME` (**done**; the re-exec uses the path, not a descriptor kept from startup). || `statx`, `getdents64`, `dirent64` | Files folder sizes, IPC socket check, `session_restart` | `fstatat` behind `platform.fs.stat` (**done** for the IPC socket check and `session_restart`). The folder-size walk still reads with `getdents64`: it refuses on FreeBSD (`getdirentries` or `readdir`, to do). || `/proc/self/fd`, `fdinfo` | spawn paths; fd-as-path opens in `files/properties`, `pdf/print.c`, `pdf/sandbox.c`, `files/terminal/child.c` | `closefrom` for spawn paths; the path form needs `fdescfs` or `*at` calls on the fd, per site. |-| `/proc/<pid>/…`, `/proc/stat`, `/proc/meminfo` | system monitor, `ipc/processes.zig`, `placeholder_match` (parent chain), `session_restart` (exe), `detectSandbox` (`root/.flatpak-info`; no Flatpak on FreeBSD, expect "not sandboxed"), editor memory probe, supervisor teardown tree | libprocstat / `kern.proc` sysctls behind a collector backend (P.6); `KERN_PROC_PATHNAME` takes a pid. procfs is optional on FreeBSD. |+| `/proc/<pid>/…`, `/proc/stat`, `/proc/meminfo` | system monitor, `ipc/processes.zig`, `placeholder_match` (parent chain), `session_restart` (exe), `detectSandbox` (`root/.flatpak-info`; no Flatpak on FreeBSD, expect "not sandboxed"), editor memory probe, supervisor teardown tree | Behind `system_monitor/proc.zig` (**interface done**, P.6), which the monitor, `ipc/processes.zig` and `placeholder_match` use; its FreeBSD backend is a stub that reports "unavailable" until phase 3 (`kern.proc` sysctls or libprocstat; `KERN_PROC_PATHNAME` takes a pid; procfs is optional on FreeBSD). The others stay: a failed read means "not sandboxed" (`detectSandbox`) or no memory check (editor), `session_restart` is a Linux install tool, the supervisor's walk is phase 2. || `pty.h`, `SCM_CREDENTIALS`, `/proc` walks | terminal engine | `libutil.h` is included and `util` linked, but `ft_start` refuses on FreeBSD: porting the shell channel's per-message check and the session teardown walk (`kern.proc` by session) needs a FreeBSD to test on. || `renameat2` | ~9 sites: Files ops, Editor, Images, screenshots, desktop watcher, theme helper, torrent helper | `link` + `unlink` for no-replace, behind `platform.fs.renameNoReplace` (**done** for the Zig sites; the theme helper's `RENAME_EXCHANGE` and the transfers helper stay Linux only). || `DRM_IOCTL_VERSION` | `Output.zig` | libdrm `drmGetVersion`; skipped on FreeBSD for now (only a hypervisor-GPU workaround). |@@ -167,10 +174,21 @@ Done:two seccomp policy tables and `battery_tests`.5. (filters) The PDF and theme helper syscall filters are built by`platform/seccomp.zig`, verdict for verdict identical to what they replaced.+6. (process list) `system_monitor/proc.zig` is the interface to the OS:+ `proc_common.zig` has the types and arithmetic, `proc_linux.zig` reads+ `/proc` (the old code, moved), `proc_freebsd.zig` reports "unavailable" (the+ monitor shows its status line, `get_processes` finds no samples). `Stat`+ carries the parent pid, so `placeholder_match` no longer opens `/proc`.7. (paths) No fixed `/usr/bin` tool path in the shell; `pkexec` and`systemctl` use `platform.tool.system` on purpose (a user-writable `PATH`must not capture a password); `XDG_DATA_DIRS` and the CUPS socket default- correctly.+ correctly. `-Dsysconfdir` (`/etc`; `/usr/local/etc` when targeting FreeBSD)+ and `-Drundir` (`/run`; `/var/run`) in `build/install_paths.zig` cover+ `rediwm/dm.conf` and `greeter.toml`, the `pam.d/rediwm` lock policy+ (`auth.c` gets `-DREDIWM_SYSCONFDIR`), CUPS's `client.conf` and the DM's+ marker directory; the polkit helper search list gained+ `/usr/local/lib/polkit-1` and `/usr/local/libexec`. Linux defaults are+ unchanged (checked with `strings`).8. No GNU-only `install -t` or `cp -T` in the build.9. `platform.peer` and `peer.h` replace five `SO_PEERCRED` sites.10. Linux-only headers sit under `#ifdef __linux__` in `libc.h`; Zig's bundled@@ -186,18 +204,15 @@ Open:ABI 3 required, fails closed; theme helper: optionally writable root and`/usr` executable, runs without Landlock on older kernels), so settle whatit promises before moving either. Security work: needs its own review.-6. **Process listing:** `/proc` parsing behind the system monitor's collector- interface (shared with `ipc/processes.zig`); every `/proc` reader in the- table needs a `platform` or collector entry point.-7. **Paths left:** the fixed `/etc` and `/run` paths (`/etc/rediwm/dm.conf` and- `greeter.toml`, `/etc/pam.d/rediwm*`, `/etc/xdg`, `/etc/cups/client.conf`,- `/run/polkit/agent-helper.socket`, `/run/rediwm-dm/`) want a sysconfdir and- rundir option (`/usr/local/etc`); the polkit helper's directory list- (`polkit/native.c`) needs `/usr/local/lib/polkit-1` and- `/usr/local/libexec` (phase 1); the cupsd probe (`printing/platform.zig`)- needs `/usr/local/sbin` and the accounts helper's candidate lists need- `pw(8)` (phase 3); `/etc/login.defs` (two places) has no FreeBSD- counterpart (`login.conf`).+7. **Paths left:** the cupsd probe (`printing/platform.zig`) needs+ `/usr/local/sbin` and the accounts helper's candidate lists need `pw(8)`+ (phase 3). Kept on purpose: `/etc/xdg` (the XDG default, read by GLib and+ xdg-desktop-portal; set `XDG_CONFIG_DIRS` where a port differs) and+ `/etc/login.defs` (both readers fall back to the usual UID range, which fits+ FreeBSD's). Phase 2 decides `/run/polkit/agent-helper.socket`: it is+ systemd's helper socket, and the agent could start the setuid helper itself+ (`rediwm_polkit_spawn`). `/etc/pam.d` and `/run/rediwm-dm` are written by+ the Linux installers only; FreeBSD packaging is phase 4.9. **Review** of the IPC allowance check that P.9 touched.### 0. Spike (FreeBSD)@@ -214,7 +229,8 @@ GLES2 path works there.is left is to run it. `rediwm-session` and `rediwm-dm` are not built onFreeBSD (`-Dlogin-session`, default off there) until phases 2 and 4. Hide NM,BlueZ, PPD, UDisks, app scopes; PDF and theme helper refuse (done); the-Files folder-size column stays empty and its terminal refuses. List the FreeBSD packages the build needs (the outside build stopped+System Monitor lists nothing (its backend is a stub); the Files folder-size+column stays empty and its terminal refuses. List the FreeBSD packages the build needs (the outside build stoppedon a missing `libtorrent-rasterbar`). Goal: `rediwm` and the apps start in aseatd session and the headless integration suites run.@@ -237,18 +253,21 @@ release tarball or a port (D6); FreeBSD in `make-release.sh` verification.## Decisions-* **D1 Target release:** 15.x only (native inotify, timerfd) or 14.x too- (kqueue vnode watching, more fallbacks). Recommend 15.x only; 15.1 has the- headers (see above).-* **D2 DM in the first release:** recommend no.-* **D3 Network:** hide, or a wpa_supplicant control-socket backend later.- Recommend hide.-* **D4 Sandboxed apps before Capsicum:** refuse (recommended, matches fail- closed) or allow with a warning.-* **D5 Power backend:** ConsoleKit2, or our own polkit-gated helper calling- `shutdown`/`acpiconf`. Recommend ConsoleKit2.+D1–D5 were made on 2026-11-05.++* **D1 Target release: 15.x only.** Native inotify and timerfd; 14.x would need+ kqueue vnode watching and more fallbacks. 15.1 has the headers (see above).+* **D2 DM in the first release: no.**+* **D3 Network: hide** the NetworkManager and BlueZ items. A wpa_supplicant+ control-socket backend may follow later.+* **D4 Sandboxed apps before Capsicum: refuse.** Matches fail closed, and is+ already implemented (the PDF viewer and the theme helper return `ENOTSUP`).+* **D5 Power backend: ConsoleKit2**, not our own polkit-gated helper calling+ `shutdown`/`acpiconf`.* **D6 Distribution:** prebuilt tarball like the Linux releases, or a port in`x11-wm`. Decide after phase 2.+* **D7 Name collation:** accept FreeBSD libc's order (done, matches `ls`) or+ ship our own for Latin and Cyrillic. Recommend accept until a user asks.## Validationdiff --git a/src/Server.zig b/src/Server.zigindex 0e0f051..1f29ca7 100644--- a/src/Server.zig+++ b/src/Server.zig@@ -357,11 +357,11 @@ pub fn init(server: *Server, scale: ?f32, icon_theme_cfg: icon_theme.Config, io:}/// The greeter never writes a config: REDIWM_CONFIG, else the administrator's-/// /etc/rediwm/greeter.toml, else built-in defaults.+/// <sysconfdir>/rediwm/greeter.toml, else built-in defaults.pub fn loadGreeterConfig(io: std.Io, environ: std.process.Environ) !config_loader.Config {const allocator = @import("main.zig").gpa;const path = if (environ.getPosix("REDIWM_CONFIG")) |p| (if (p.len > 0) p else null) else null;- const system = "/etc/rediwm/greeter.toml";+ const system = @import("install_paths").sysconfdir ++ "/rediwm/greeter.toml";if (path) |p| return parseGreeterFile(p, allocator, io);std.Io.Dir.cwd().access(io, system, .{}) catch return config_loader.default(allocator);return parseGreeterFile(system, allocator, io);diff --git a/src/accounts/model.zig b/src/accounts/model.zigindex cd8db2e..1ed5c92 100644--- a/src/accounts/model.zig+++ b/src/accounts/model.zig@@ -99,7 +99,7 @@ pub fn load(a: std.mem.Allocator, io: std.Io) !Snapshot {user.groups = try memberships.toOwnedSlice(a);}- const config = std.Io.Dir.cwd().readFileAlloc(io, "/etc/rediwm/dm.conf", a, .limited(64 * 1024)) catch "";+ const config = std.Io.Dir.cwd().readFileAlloc(io, @import("install_paths").sysconfdir ++ "/rediwm/dm.conf", a, .limited(64 * 1024)) catch "";defer if (config.len > 0) a.free(config);const auto = try parseAutologin(a, config);const sessions = ws.loadSessions(a, io, @import("install_paths").data_dirs, @import("install_paths").search_path) catch &.{};diff --git a/src/accounts_helper/main.zig b/src/accounts_helper/main.zigindex b98e048..0409b84 100644--- a/src/accounts_helper/main.zig+++ b/src/accounts_helper/main.zig@@ -18,7 +18,8 @@ const Request = struct {};const a = std.heap.c_allocator;-const dm_conf_path = "/etc/rediwm/dm.conf";+const conf_dir = std.fmt.comptimePrint("{s}/rediwm", .{@import("install_paths").sysconfdir});+const dm_conf_path = conf_dir ++ "/dm.conf";const session_dirs = ws.standard_data_dirs;pub fn main(init: std.process.Init) u8 {@@ -362,7 +363,7 @@ fn writeAutologin(io: std.Io, user: ?[]const u8, session: ?[]const u8) !void {defer a.free(old);const new = try dm_config.rewriteAutologin(a, old, user, session);defer a.free(new);- const temp = try std.fmt.allocPrintSentinel(a, "/etc/rediwm/.dm.conf.{d}.tmp", .{c.getpid()}, 0);+ const temp = try std.fmt.allocPrintSentinel(a, conf_dir ++ "/.dm.conf.{d}.tmp", .{c.getpid()}, 0);defer a.free(temp);const fd = c.open(temp.ptr, c.O_WRONLY | c.O_CREAT | c.O_EXCL | c.O_CLOEXEC, @as(c_uint, 0o644));if (fd < 0) return error.TempFileFailed;@@ -380,9 +381,9 @@ fn writeAutologin(io: std.Io, user: ?[]const u8, session: ?[]const u8) !void {if (c.fsync(fd) != 0) return error.ConfigSyncFailed;if (c.rename(temp.ptr, dm_conf_path) != 0) return error.ConfigRenameFailed;ok = true;- const dirfd = c.open("/etc/rediwm", c.O_RDONLY | c.O_DIRECTORY | c.O_CLOEXEC);+ const dirfd = c.open(conf_dir, c.O_RDONLY | c.O_DIRECTORY | c.O_CLOEXEC);if (dirfd >= 0) {defer _ = c.close(dirfd);- if (c.fsync(dirfd) != 0) std.log.warn("could not sync /etc/rediwm after automatic-login update", .{});+ if (c.fsync(dirfd) != 0) std.log.warn("could not sync " ++ conf_dir ++ " after automatic-login update", .{});}}diff --git a/src/dm/daemon.zig b/src/dm/daemon.zigindex b7e8236..61a6a98 100644--- a/src/dm/daemon.zig+++ b/src/dm/daemon.zig@@ -58,7 +58,7 @@ pub const Daemon = struct {gpa: std.mem.Allocator = std.heap.c_allocator,is_test: bool = false,confdir: ?[]const u8 = null,- marker_path: []const u8 = "/run/rediwm-dm/autologin-done",+ marker_path: []const u8 = @import("install_paths").rundir ++ "/rediwm-dm/autologin-done",search_dirs: []const []const u8 = ws.standard_data_dirs,range: ws.UidRange = .{},relay: state_mod.Relay,diff --git a/src/dm/main.zig b/src/dm/main.zigindex b7b1d38..9bc6af3 100644--- a/src/dm/main.zig+++ b/src/dm/main.zig@@ -39,8 +39,8 @@ pub fn main(init: std.process.Init) u8 {var greeter_fd: c_int = -1;var is_test = false;var confdir: ?[]const u8 = null;- var conf_path: []const u8 = "/etc/rediwm/dm.conf";- var marker_path: []const u8 = "/run/rediwm-dm/autologin-done";+ var conf_path: []const u8 = @import("install_paths").sysconfdir ++ "/rediwm/dm.conf";+ var marker_path: []const u8 = @import("install_paths").rundir ++ "/rediwm-dm/autologin-done";var marker_override = false;var data_dir: ?[]const u8 = null;diff --git a/src/files/collation.zig b/src/files/collation.zigindex f32e334..0f1cd39 100644--- a/src/files/collation.zig+++ b/src/files/collation.zig@@ -1,6 +1,7 @@//! Private name collation. Keys are frozen with each listing so UI sorting//! never calls libc, changes the process locale or races a worker update.const std = @import("std");+const builtin = @import("builtin");const c = @import("c");pub const Locale = struct {@@ -97,11 +98,19 @@ test "C name collation preserves byte order for a mixed name list" {try checkOrder("C", &.{ "Apfel", "Zebra", "apple", "Äpfel", "Élan", "Ёж", "Ель", "Яблоко" });}+/// The expected orders are glibc's. FreeBSD's tables differ (see+/// docs/plans/freebsd.md); there `strxfrm_l` still agrees with `strcoll_l`.+fn needsGlibcTables() !void {+ if (builtin.os.tag != .linux) return error.SkipZigTest;+}+test "German name collation places accented names beside their base letters" {+ try needsGlibcTables();try checkOrder("de_DE.UTF-8", &.{ "Apfel", "Äpfel", "apple", "Élan", "Zebra", "Ёж", "Ель", "Яблоко" });}test "Russian name collation orders Cyrillic names and yo with ye" {+ try needsGlibcTables();try checkOrder("ru_RU.UTF-8", &.{ "Apfel", "Äpfel", "apple", "Élan", "Zebra", "Еж", "Ёж", "Ель", "Яблоко" });}diff --git a/src/ipc/processes.zig b/src/ipc/processes.zigindex 5ab4c89..2d888e6 100644--- a/src/ipc/processes.zig+++ b/src/ipc/processes.zig@@ -7,6 +7,7 @@ const Client = @import("server.zig").Client;const Server = @import("../Server.zig");const gpa = @import("../main.zig").gpa;const c = @import("c");+const proc = @import("../system_monitor/proc.zig");pub const Job = struct {arena: std.heap.ArenaAllocator,@@ -34,8 +35,8 @@ pub const Job = struct {}fn run(job: *Job) void {defer job.unref();- const ticks = c.sysconf(c._SC_CLK_TCK);- const page = c.sysconf(c._SC_PAGESIZE);+ const ticks = proc.ticksPerSecond();+ const page = proc.pageSize();const a = job.arena.allocator();const first = a.alloc(?Sample, job.rows.len) catch {job.complete();@@ -58,7 +59,7 @@ pub const Job = struct {if (prev.start != after.start) continue;row.running = true;row.start_ticks = after.start;- if (page > 0) row.rss_bytes = std.math.mul(u64, after.rss, @intCast(page)) catch null;+ if (page > 0) row.rss_bytes = std.math.mul(u64, after.rss, page) catch null;if (ticks > 0 and elapsed > 0 and after.cpu >= prev.cpu)row.cpu_percent = @as(f64, @floatFromInt(after.cpu - prev.cpu)) * 100 * 1_000_000_000 /(@as(f64, @floatFromInt(ticks)) * @as(f64, @floatFromInt(elapsed)));@@ -75,7 +76,7 @@ pub const Job = struct {const Sample = struct { cpu: u64, start: u64, rss: u64 };fn readSample(pid: i32) ?Sample {var buf: [4096]u8 = undefined;- const stat = @import("../system_monitor/proc.zig").readStat(pid, &buf) orelse return null;+ const stat = proc.readStat(pid, &buf) orelse return null;return .{ .cpu = stat.cpu, .start = stat.start, .rss = stat.rss };}diff --git a/src/placeholder_match.zig b/src/placeholder_match.zigindex c56b785..f4d1207 100644--- a/src/placeholder_match.zig+++ b/src/placeholder_match.zig@@ -2,25 +2,10 @@//!//! Match real windows to placeholders using layered criteria (most trustworthy first)://! 1. Activation token-//! 2. Process ID / /proc ppid chain walking+//! 2. Process ID / parent chain walking//! 3. App ID / desktop entry stem matchingconst std = @import("std");--pub fn parsePpidFromStat(stat_content: []const u8) ?i32 {- // Linux /proc/<pid>/stat format:- // pid (comm) state ppid pgrp session tty_nr ...- // Note that comm can contain arbitrary characters including parentheses and spaces.- const last_paren = std.mem.lastIndexOfScalar(u8, stat_content, ')') orelse return null;- if (last_paren + 2 >= stat_content.len) return null;-- // After ')': space, state character, space, ppid- const remainder = std.mem.trimStart(u8, stat_content[last_paren + 1 ..], " \t");- // Remainder begins with state character (e.g. 'S' or 'R')- var it = std.mem.splitScalar(u8, remainder, ' ');- _ = it.next() orelse return null; // skip state- const ppid_str = it.next() orelse return null;- return std.fmt.parseInt(i32, ppid_str, 10) catch null;-}+const proc = @import("system_monitor/proc.zig");pub fn matchesPidChain(client_pid: i32, target_pid: i32) bool {if (client_pid <= 0 or target_pid <= 0) return false;@@ -29,17 +14,8 @@ pub fn matchesPidChain(client_pid: i32, target_pid: i32) bool {var cur_pid = client_pid;var depth: usize = 0;while (depth < 5) : (depth += 1) {- var path_buf: [64:0]u8 = undefined;- const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/stat", .{cur_pid}, 0) catch break;- const fd = std.posix.openat(std.posix.AT.FDCWD, path, .{- .ACCMODE = .RDONLY,- .CLOEXEC = true,- }, 0) catch break;- defer _ = std.c.close(fd);-var stat_buf: [1024]u8 = undefined;- const bytes_read = std.posix.read(fd, &stat_buf) catch break;- const ppid = parsePpidFromStat(stat_buf[0..bytes_read]) orelse break;+ const ppid = (proc.readStat(cur_pid, &stat_buf) orelse break).ppid;if (ppid <= 1) break;if (ppid == target_pid) return true;cur_pid = ppid;@@ -82,20 +58,6 @@ pub fn matchesToken(candidate_token: []const u8, placeholder_token: []const u8)return std.mem.eql(u8, candidate_token, placeholder_token);}-test "parse ppid from /proc/<pid>/stat" {- // Normal process stat- const sample1 = "12345 (bash) S 6789 12345 12345 34816 12345 4194304 2337 0 0 0 0 0 0 0 20 0 1 0";- try std.testing.expectEqual(@as(?i32, 6789), parsePpidFromStat(sample1));-- // Process comm with parentheses and spaces inside- const sample2 = "999 (my (complex) app) R 1001 999 999 0 0 0 0 0 0 0";- try std.testing.expectEqual(@as(?i32, 1001), parsePpidFromStat(sample2));-- // Malformed- try std.testing.expect(parsePpidFromStat("") == null);- try std.testing.expect(parsePpidFromStat("not valid stat") == null);-}-test "app_id matching" {try std.testing.expect(matchesAppId("foot", null, "foot.desktop"));try std.testing.expect(matchesAppId("FOOT", null, "foot.desktop"));diff --git a/src/polkit/native.c b/src/polkit/native.cindex 6b52376..f221b55 100644--- a/src/polkit/native.c+++ b/src/polkit/native.c@@ -81,7 +81,8 @@ void rediwm_polkit_secret_free(void *p) {/* The caller registers the returned child with its event-loop pidfd watcher. */int rediwm_polkit_spawn(const char *user, pid_t *out) {- const char *paths[] = {"/usr/lib/polkit-1/polkit-agent-helper-1", "/usr/libexec/polkit-agent-helper-1"};+ const char *paths[] = {"/usr/lib/polkit-1/polkit-agent-helper-1", "/usr/libexec/polkit-agent-helper-1",+ "/usr/local/lib/polkit-1/polkit-agent-helper-1", "/usr/local/libexec/polkit-agent-helper-1"};const char *path = NULL;for (size_t i = 0; i < sizeof paths / sizeof paths[0]; ++i) {struct stat st;diff --git a/src/printing/cups.zig b/src/printing/cups.zigindex fe0674e..7dd6587 100644--- a/src/printing/cups.zig+++ b/src/printing/cups.zig@@ -83,7 +83,7 @@ pub fn server(a: A, io: std.Io, env: std.process.Environ) ![]const u8 {const mem = arena.allocator();var configured: []const u8 = localSocket(io);var encryption: []const u8 = "IfRequested";- const system = try readClientConfig(mem, io, "/etc/cups/client.conf");+ const system = try readClientConfig(mem, io, @import("install_paths").sysconfdir ++ "/cups/client.conf");const system_config = try clientConfig(system);configured = system_config.server orelse configured;encryption = system_config.encryption orelse encryption;diff --git a/src/session/auth.c b/src/session/auth.cindex 7534790..914cfff 100644--- a/src/session/auth.c+++ b/src/session/auth.c@@ -11,6 +11,11 @@#include <unistd.h>#include <pwd.h>+/* The build passes -DREDIWM_SYSCONFDIR (build/install_paths.zig); /etc on Linux. */+#ifndef REDIWM_SYSCONFDIR+#define REDIWM_SYSCONFDIR "/etc"+#endif+/* No test password, environment-selected service, or privileged compositor.* PAM runs away from the Wayland thread. Only a completed successful auth AND* account check can yield success. The UID, never $USER, selects the account. */@@ -71,8 +76,8 @@ static void *authenticate(void *data) {struct pam_conv conv = {converse, auth};pam_handle_t *pam = NULL;/* login is the distro-provided local-login policy. An administrator can- * provide a dedicated /etc/pam.d/rediwm policy instead. */- const char *service = access("/etc/pam.d/rediwm", F_OK) == 0 ? "rediwm" : "login";+ * provide a dedicated <sysconfdir>/pam.d/rediwm policy instead. */+ const char *service = access(REDIWM_SYSCONFDIR "/pam.d/rediwm", F_OK) == 0 ? "rediwm" : "login";int rc = pam_start(service, auth->user, &conv, &pam);if (rc == PAM_SUCCESS) rc = pam_authenticate(pam, PAM_DISALLOW_NULL_AUTHTOK);if (rc == PAM_SUCCESS) rc = pam_acct_mgmt(pam, PAM_DISALLOW_NULL_AUTHTOK);diff --git a/src/system_monitor/AGENTS.md b/src/system_monitor/AGENTS.mdindex 1adf01c..d568f97 100644--- a/src/system_monitor/AGENTS.md+++ b/src/system_monitor/AGENTS.md@@ -3,6 +3,13 @@* `proc.zig`, `collector.zig`, `model.zig` and `actions.zig` have no compositoror UI dependencies. IPC reuses the stat reader but keeps its window-only,request-driven sampling contract.+* **`proc.zig` is the interface to the OS.** The record types and arithmetic+ are `proc_common.zig`; one backend reads them: `proc_linux.zig` (`/proc`, a+ `Process` holds the `/proc/<pid>` directory open) or `proc_freebsd.zig`+ (reports "unavailable" until phase 3 of `docs/plans/freebsd.md`). Never read+ `/proc` outside a backend; a new OS needs `Process`, `List`, `cpuTotals`,+ `memoryTotals` and `ticksPerSecond`. The Linux parsers are pure and tested+ everywhere through `proc_linux.zig`.* A snapshot owns its arena. The worker publishes under its mutex through aneventfd; the UI takes ownership. A generation change cancels enumeration andpublication, resets CPU baselines, and wakes the worker. Inactive workersdiff --git a/src/system_monitor/actions.zig b/src/system_monitor/actions.zigindex 4f976ec..7440fdf 100644--- a/src/system_monitor/actions.zig+++ b/src/system_monitor/actions.zig@@ -8,17 +8,17 @@ pub const Kind = enum { end, force };pub fn execute(identity: proc.Identity, kind: Kind) !void {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);- defer _ = c.close(dir);+ // Open the process record AFTER the handle. If PID reuse occurs between+ // them, the old handle reports the exit and the final liveness gate fails.+ const entry = try proc.Process.open(identity.pid);+ defer entry.close();var stat_buf: [4096]u8 = undefined;- const stat = proc.parseStat(try proc.readAt(dir, "stat", &stat_buf)) orelse return error.IdentityUnavailable;+ const stat = try entry.stat(&stat_buf);if (stat.start != identity.start) return error.ProcessExited;var status_buf: [16384]u8 = undefined;- const uids = proc.parseUids(try proc.readAt(dir, "status", &status_buf)) orelse return error.IdentityUnavailable;+ const uids = try entry.uids(&status_buf);if (!proc.owned(uids, c.getuid())) return error.PermissionDenied;- if (try proc.protectedAt(dir, identity.pid)) return error.ProtectedProcess;+ if (try proc.isProtected(entry, identity.pid)) return error.ProtectedProcess;// The handle names the task it was opened on, not whichever task// currently occupies /proc/PID.const live = process.pid() catch return error.IdentityUnavailable;diff --git a/src/system_monitor/collector.zig b/src/system_monitor/collector.zigindex 53132c7..d625cf0 100644--- a/src/system_monitor/collector.zig+++ b/src/system_monitor/collector.zig@@ -38,14 +38,14 @@ pub fn sample(cancelled: *const std.atomic.Value(u64), generation: u64) !*Snapsherrdefer snapshot.deinit();const arena = snapshot.arena.allocator();var buf: [65536]u8 = undefined;- if (proc.readAt(c.AT_FDCWD, "/proc/stat", &buf)) |bytes| snapshot.cpu = proc.parseCpu(bytes) else |_| {}- if (proc.readAt(c.AT_FDCWD, "/proc/meminfo", &buf)) |bytes| snapshot.memory = proc.parseMemory(bytes) else |_| {}- const dir = c.opendir("/proc") orelse {+ snapshot.cpu = proc.cpuTotals(&buf);+ snapshot.memory = proc.memoryTotals(&buf);+ var list = proc.List.open() orelse {snapshot.failed = true;return snapshot;};- defer _ = c.closedir(dir);- const page_size = c.sysconf(c._SC_PAGESIZE);+ defer list.close();+ const page_size = proc.pageSize();var rows: std.ArrayList(Process) = .empty;var users: std.AutoHashMapUnmanaged(u32, []const u8) = .empty;// Avoid NSS here: a directory service outage must never prevent stopping@@ -60,33 +60,31 @@ pub fn sample(cancelled: *const std.atomic.Value(u64), generation: u64) !*Snapshtry users.put(arena, uid, try safeName(arena, user));}} else |_| {}- while (c.readdir(dir)) |entry| {+ while (list.next()) |pid| {if (cancelled.load(.acquire) != generation) return error.Cancelled;- const name = std.mem.sliceTo(entry.*.d_name[0..], 0);- const pid = std.fmt.parseInt(i32, name, 10) catch continue;- if (pid <= 0) continue;if (rows.items.len >= 131072) {snapshot.truncated = true;break;}- const process_dir = proc.openProcess(pid) catch {+ const process = proc.Process.open(pid) catch {snapshot.unavailable += 1;continue;};- defer _ = c.close(process_dir);- const stat = proc.parseStat(proc.readAt(process_dir, "stat", &buf) catch {- snapshot.unavailable += 1;+ defer process.close();+ const stat = process.stat(&buf) catch |err| {+ // Gone or unreadable counts as unavailable; a malformed record is skipped.+ if (err != error.IdentityUnavailable) snapshot.unavailable += 1;continue;- }) orelse continue;+ };const process_name = try safeName(arena, stat.name);- const uids = if (proc.readAt(process_dir, "status", &buf)) |bytes| proc.parseUids(bytes) else |_| null;+ const uids = process.uids(&buf) catch null;const user = if (uids) |ids| blk: {if (users.get(ids[0])) |value| break :blk value;const value = try std.fmt.allocPrint(arena, "{d}", .{ids[0]});try users.put(arena, ids[0], value);break :blk value;} else "Unavailable";- const protected = proc.protectedAt(process_dir, pid) catch true;+ const protected = proc.isProtected(process, pid) catch true;try rows.append(arena, .{.identity = .{ .pid = pid, .start = stat.start },.name = process_name,@@ -94,7 +92,7 @@ pub fn sample(cancelled: *const std.atomic.Value(u64), generation: u64) !*Snapsh.uids = uids,.state = stat.state,.cpu_ticks = stat.cpu,- .resident_bytes = if (page_size > 0) std.math.mul(u64, stat.rss, @intCast(page_size)) catch null else null,+ .resident_bytes = if (page_size > 0) std.math.mul(u64, stat.rss, page_size) catch null else null,.protected = protected,});}@@ -169,8 +167,7 @@ pub const Worker = struct {var last_cpu: ?proc.Cpu = null;var observed: u64 = std.math.maxInt(u64);var deadline: u64 = 0;- const hz_raw = c.sysconf(c._SC_CLK_TCK);- const hz: u64 = @intCast(@max(0, hz_raw));+ const hz = proc.ticksPerSecond();while (!self.stopping.load(.acquire)) {const generation = self.generation.load(.acquire);if (generation != observed) {diff --git a/src/system_monitor/proc.zig b/src/system_monitor/proc.zigindex cb1f1b6..3828a52 100644--- a/src/system_monitor/proc.zig+++ b/src/system_monitor/proc.zig@@ -1,175 +1,55 @@-//! Bounded Linux proc readers. No compositor, Wayland or UI dependencies.-const std = @import("std");-pub const c = @import("c");--pub const Identity = struct {- pid: i32,- start: u64,- pub fn eql(a: Identity, b: Identity) bool {- return a.pid == b.pid and a.start == b.start;- }+//! The process list the System Monitor and the IPC `processes` command read.+//! This file is the interface: the record types and arithmetic come from+//! `proc_common.zig`, the reading from one backend chosen at compile time+//! (`proc_linux.zig`; `proc_freebsd.zig` reports "unavailable" until phase 3 of+//! docs/plans/freebsd.md). A backend provides:+//!+//! * `Process`: `open(pid)`, `close`, `stat(buf)`, `uids(buf)`, `exePath(buf)`.+//! One open `Process` describes one task, so its three reads agree.+//! * `List`: `open()`, `next()` (a pid), `close()`.+//! * `cpuTotals(buf)`, `memoryTotals(buf)`, `ticksPerSecond()`.+//!+//! No compositor, Wayland or UI dependencies.+const builtin = @import("builtin");+const common = @import("proc_common.zig");+const backend = switch (builtin.os.tag) {+ .linux => @import("proc_linux.zig"),+ .freebsd => @import("proc_freebsd.zig"),+ else => @compileError("the process list is not ported to this OS (docs/plans/freebsd.md)"),};-pub const Stat = struct { name: []const u8, state: u8, cpu: u64, start: u64, rss: u64 };--/// comm may contain spaces, newlines and closing parentheses. Field 3 starts-/// after the LAST closing parenthesis; fields 14/15/22/24 are CPU/start/RSS.-pub fn parseStat(bytes: []const u8) ?Stat {- const begin = std.mem.indexOfScalar(u8, bytes, '(') orelse return null;- const end = std.mem.lastIndexOfScalar(u8, bytes, ')') orelse return null;- if (end <= begin) return null;- var fields = std.mem.tokenizeAny(u8, bytes[end + 1 ..], " \n");- var out: Stat = .{ .name = bytes[begin + 1 .. end], .state = '?', .cpu = 0, .start = 0, .rss = 0 };- var index: usize = 0;- while (fields.next()) |field| : (index += 1) switch (index) {- 0 => {- if (field.len != 1) return null;- out.state = field[0];- },- 11, 12 => out.cpu +|= std.fmt.parseInt(u64, field, 10) catch return null,- 19 => out.start = std.fmt.parseInt(u64, field, 10) catch return null,- 21 => {- const rss = std.fmt.parseInt(i64, field, 10) catch return null;- out.rss = @intCast(@max(0, rss));- return out;- },- else => {},- };- return null;-}--pub fn readAt(dir: c_int, path: [*:0]const u8, buf: []u8) ![]const u8 {- const fd = c.openat(dir, path, c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW);- if (fd < 0) return switch (std.posix.errno(fd)) {- .ACCES, .PERM => error.PermissionDenied,- .NOENT, .SRCH => error.ProcessExited,- else => error.ReadFailed,- };- defer _ = c.close(fd);- var len: usize = 0;- while (len < buf.len) {- const n = c.read(fd, buf.ptr + len, buf.len - len);- if (n < 0 and std.posix.errno(n) == .INTR) continue;- if (n < 0) return error.ReadFailed;- if (n == 0) return buf[0..len];- len += @intCast(n);- }- return error.DataTooLarge;-}--pub fn openProcess(pid: i32) !c_int {- if (pid <= 0) return error.ProcessExited;- var buf: [64]u8 = undefined;- const path = try std.fmt.bufPrintSentinel(&buf, "/proc/{d}", .{pid}, 0);- const fd = c.open(path, c.O_DIRECTORY | c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW);- if (fd < 0) return switch (std.posix.errno(fd)) {- .ACCES, .PERM => error.PermissionDenied,- .NOENT, .SRCH => error.ProcessExited,- else => error.ReadFailed,- };- return fd;-}+pub const c = common.c;+pub const Error = common.Error;+pub const Identity = common.Identity;+pub const Stat = common.Stat;+pub const Uids = common.Uids;+pub const Cpu = common.Cpu;+pub const Memory = common.Memory;+pub const owned = common.owned;+pub const protectedName = common.protectedName;+pub const cpuPercent = common.cpuPercent;+pub const processPercent = common.processPercent;+pub const readAt = common.readAt;+pub const pageSize = common.pageSize;+pub const nowNs = common.nowNs;++pub const Process = backend.Process;+pub const List = backend.List;+pub const cpuTotals = backend.cpuTotals;+pub const memoryTotals = backend.memoryTotals;+pub const ticksPerSecond = backend.ticksPerSecond;++/// One process's stat, or null if it is gone or unreadable. `name` points into `buf`.pub fn readStat(pid: i32, buf: []u8) ?Stat {- const dir = openProcess(pid) catch return null;- defer _ = c.close(dir);- return parseStat(readAt(dir, "stat", buf) catch return null);-}--pub const Uids = [4]u32;-pub fn parseUids(bytes: []const u8) ?Uids {- var lines = std.mem.splitScalar(u8, bytes, '\n');- while (lines.next()) |line| {- if (!std.mem.startsWith(u8, line, "Uid:")) continue;- var values = std.mem.tokenizeAny(u8, line[4..], " \t");- var out: Uids = undefined;- for (&out) |*uid| uid.* = std.fmt.parseInt(u32, values.next() orelse return null, 10) catch return null;- return out;- }- return null;-}--pub fn owned(uids: Uids, uid: u32) bool {- for (uids) |value| if (value != uid) return false;- return true;+ const process = Process.open(pid) catch return null;+ defer process.close();+ return process.stat(buf) catch null;}-pub fn protectedName(name: []const u8) bool {- const clean = if (std.mem.endsWith(u8, name, " (deleted)")) name[0 .. name.len - " (deleted)".len] else name;- const base = std.fs.path.basename(clean);- inline for (.{ "rediwm", "rediwm-session", "rediwm-dm", "rediwm-accounts-helper", "rediwm-polkit-agent" }) |protected| {- if (std.mem.eql(u8, base, protected)) return true;- }- return false;-}--pub fn protectedAt(dir: c_int, pid: i32) !bool {+/// Session processes and this one must never be signalled from the monitor.+/// An unreadable executable is an error, not "not protected".+pub fn isProtected(process: Process, pid: i32) Error!bool {if (pid <= 1 or pid == c.getpid()) return true;var buf: [4096]u8 = undefined;- const n = c.readlinkat(dir, "exe", &buf, buf.len);- if (n < 0 or n == buf.len) return error.IdentityUnavailable;- return protectedName(buf[0..@intCast(n)]);-}--pub const Cpu = struct { total: u64, idle: u64 };-pub fn parseCpu(bytes: []const u8) ?Cpu {- var fields = std.mem.tokenizeAny(u8, bytes[0 .. std.mem.indexOfScalar(u8, bytes, '\n') orelse bytes.len], " \t");- if (!std.mem.eql(u8, fields.next() orelse return null, "cpu")) return null;- var out: Cpu = .{ .total = 0, .idle = 0 };- var count: usize = 0;- // guest and guest_nice are already included in user/nice.- while (fields.next()) |field| : (count += 1) {- if (count == 8) break;- const ticks = std.fmt.parseInt(u64, field, 10) catch return null;- out.total +|= ticks;- if (count == 3 or count == 4) out.idle +|= ticks;- }- return if (count >= 4) out else null;-}-pub fn cpuPercent(before: Cpu, after: Cpu) ?f64 {- if (after.total <= before.total or after.idle < before.idle) return null;- const total = after.total - before.total;- return @as(f64, @floatFromInt(total -| (after.idle - before.idle))) * 100 / @as(f64, @floatFromInt(total));-}-/// Process CPU uses one core = 100%, and may exceed 100% for threaded apps.-pub fn processPercent(before: Stat, after: Stat, hz: u64, elapsed_ns: u64) ?f64 {- if (before.start != after.start or after.cpu < before.cpu or hz == 0 or elapsed_ns == 0) return null;- return @as(f64, @floatFromInt(after.cpu - before.cpu)) * 100 * 1_000_000_000 /- (@as(f64, @floatFromInt(hz)) * @as(f64, @floatFromInt(elapsed_ns)));-}--pub const Memory = struct {- total: u64,- available: u64,- swap_total: ?u64,- swap_free: ?u64,- pub fn used(self: Memory) u64 {- return self.total -| self.available;- }-};-pub fn parseMemory(bytes: []const u8) ?Memory {- var total: ?u64 = null;- var available: ?u64 = null;- var swap_total: ?u64 = null;- var swap_free: ?u64 = null;- var lines = std.mem.splitScalar(u8, bytes, '\n');- while (lines.next()) |line| {- var fields = std.mem.tokenizeAny(u8, line, " \t");- const key = fields.next() orelse continue;- const relevant = std.mem.eql(u8, key, "MemTotal:") or std.mem.eql(u8, key, "MemAvailable:") or std.mem.eql(u8, key, "SwapTotal:") or std.mem.eql(u8, key, "SwapFree:");- if (!relevant) continue;- const kb = std.fmt.parseInt(u64, fields.next() orelse return null, 10) catch return null;- if (!std.mem.eql(u8, fields.next() orelse return null, "kB")) return null;- const value = std.math.mul(u64, kb, 1024) catch return null;- if (std.mem.eql(u8, key, "MemTotal:")) total = value;- if (std.mem.eql(u8, key, "MemAvailable:")) available = value;- if (std.mem.eql(u8, key, "SwapTotal:")) swap_total = value;- if (std.mem.eql(u8, key, "SwapFree:")) swap_free = value;- }- return .{ .total = total orelse return null, .available = available orelse return null, .swap_total = swap_total, .swap_free = swap_free };-}--pub fn nowNs() u64 {- var ts: c.struct_timespec = undefined;- if (c.clock_gettime(c.CLOCK_MONOTONIC, &ts) != 0) return 0;- return @as(u64, @intCast(ts.tv_sec)) * 1_000_000_000 + @as(u64, @intCast(ts.tv_nsec));+ return protectedName(try process.exePath(&buf));}diff --git a/src/system_monitor/proc_common.zig b/src/system_monitor/proc_common.zignew file mode 100644index 0000000..64bc023--- /dev/null+++ b/src/system_monitor/proc_common.zig@@ -0,0 +1,89 @@+//! What the process list means on every OS: the record types and the pure+//! arithmetic over them. The OS-specific reading is in `proc_linux.zig` and+//! `proc_freebsd.zig`, chosen by `proc.zig`.+const std = @import("std");+pub const c = @import("c");++/// What a backend may report. `IdentityUnavailable` means the record exists but+/// is unreadable or malformed; `Unsupported` means this OS has no backend yet.+pub const Error = error{ ProcessExited, PermissionDenied, ReadFailed, DataTooLarge, IdentityUnavailable, Unsupported };++pub const Identity = struct {+ pid: i32,+ /// An opaque start stamp: with the pid it names one process for ever.+ start: u64,+ pub fn eql(a: Identity, b: Identity) bool {+ return a.pid == b.pid and a.start == b.start;+ }+};+/// CPU is in `ticksPerSecond()` units and RSS in `pageSize()` units.+pub const Stat = struct { name: []const u8, state: u8, cpu: u64, start: u64, rss: u64, ppid: i32 = 0 };++pub const Uids = [4]u32;++pub fn owned(uids: Uids, uid: u32) bool {+ for (uids) |value| if (value != uid) return false;+ return true;+}++pub fn protectedName(name: []const u8) bool {+ const clean = if (std.mem.endsWith(u8, name, " (deleted)")) name[0 .. name.len - " (deleted)".len] else name;+ const base = std.fs.path.basename(clean);+ inline for (.{ "rediwm", "rediwm-session", "rediwm-dm", "rediwm-accounts-helper", "rediwm-polkit-agent" }) |protected| {+ if (std.mem.eql(u8, base, protected)) return true;+ }+ return false;+}++pub const Cpu = struct { total: u64, idle: u64 };+pub fn cpuPercent(before: Cpu, after: Cpu) ?f64 {+ if (after.total <= before.total or after.idle < before.idle) return null;+ const total = after.total - before.total;+ return @as(f64, @floatFromInt(total -| (after.idle - before.idle))) * 100 / @as(f64, @floatFromInt(total));+}+/// Process CPU uses one core = 100%, and may exceed 100% for threaded apps.+pub fn processPercent(before: Stat, after: Stat, hz: u64, elapsed_ns: u64) ?f64 {+ if (before.start != after.start or after.cpu < before.cpu or hz == 0 or elapsed_ns == 0) return null;+ return @as(f64, @floatFromInt(after.cpu - before.cpu)) * 100 * 1_000_000_000 /+ (@as(f64, @floatFromInt(hz)) * @as(f64, @floatFromInt(elapsed_ns)));+}++pub const Memory = struct {+ total: u64,+ available: u64,+ swap_total: ?u64,+ swap_free: ?u64,+ pub fn used(self: Memory) u64 {+ return self.total -| self.available;+ }+};++pub fn readAt(dir: c_int, path: [*:0]const u8, buf: []u8) ![]const u8 {+ const fd = c.openat(dir, path, c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW);+ if (fd < 0) return switch (std.posix.errno(fd)) {+ .ACCES, .PERM => error.PermissionDenied,+ .NOENT, .SRCH => error.ProcessExited,+ else => error.ReadFailed,+ };+ defer _ = c.close(fd);+ var len: usize = 0;+ while (len < buf.len) {+ const n = c.read(fd, buf.ptr + len, buf.len - len);+ if (n < 0 and std.posix.errno(n) == .INTR) continue;+ if (n < 0) return error.ReadFailed;+ if (n == 0) return buf[0..len];+ len += @intCast(n);+ }+ return error.DataTooLarge;+}++pub fn pageSize() u64 {+ const value = c.sysconf(c._SC_PAGESIZE);+ return if (value > 0) @intCast(value) else 0;+}++pub fn nowNs() u64 {+ var ts: c.struct_timespec = undefined;+ if (c.clock_gettime(c.CLOCK_MONOTONIC, &ts) != 0) return 0;+ return @as(u64, @intCast(ts.tv_sec)) * 1_000_000_000 + @as(u64, @intCast(ts.tv_nsec));+}diff --git a/src/system_monitor/proc_freebsd.zig b/src/system_monitor/proc_freebsd.zignew file mode 100644index 0000000..3d01c60--- /dev/null+++ b/src/system_monitor/proc_freebsd.zig@@ -0,0 +1,44 @@+//! FreeBSD backend of the process list: not written yet (docs/plans/freebsd.md,+//! phase 3: `kern.proc` sysctls or libprocstat; FreeBSD has no procfs by+//! default). Everything reports "unavailable", so the System Monitor shows its+//! status line instead of rows and the IPC `processes` command finds no samples.+const common = @import("proc_common.zig");+const Error = common.Error;++pub const Process = struct {+ pub fn open(_: i32) Error!Process {+ return error.Unsupported;+ }+ pub fn close(_: Process) void {}+ pub fn stat(_: Process, _: []u8) Error!common.Stat {+ return error.Unsupported;+ }+ pub fn uids(_: Process, _: []u8) Error!common.Uids {+ return error.Unsupported;+ }+ pub fn exePath(_: Process, _: []u8) Error![]const u8 {+ return error.Unsupported;+ }+};++pub const List = struct {+ pub fn open() ?List {+ return null;+ }+ pub fn next(_: *List) ?i32 {+ return null;+ }+ pub fn close(_: *List) void {}+};++pub fn cpuTotals(_: []u8) ?common.Cpu {+ return null;+}++pub fn memoryTotals(_: []u8) ?common.Memory {+ return null;+}++pub fn ticksPerSecond() u64 {+ return 0;+}diff --git a/src/system_monitor/proc_linux.zig b/src/system_monitor/proc_linux.zignew file mode 100644index 0000000..1664453--- /dev/null+++ b/src/system_monitor/proc_linux.zig@@ -0,0 +1,154 @@+//! Linux backend of the process list: /proc. A `Process` holds the+//! `/proc/<pid>` directory open, so every file read belongs to the same task.+//! The parsers are pure functions; their tests run on every OS.+const std = @import("std");+const common = @import("proc_common.zig");+const c = common.c;+const Error = common.Error;+const Stat = common.Stat;+const Uids = common.Uids;+const Cpu = common.Cpu;+const Memory = common.Memory;+const readAt = common.readAt;++/// comm may contain spaces, newlines and closing parentheses. Field 3 starts+/// after the LAST closing parenthesis; fields 4/14/15/22/24 are PPID/CPU/start/RSS.+pub fn parseStat(bytes: []const u8) ?Stat {+ const begin = std.mem.indexOfScalar(u8, bytes, '(') orelse return null;+ const end = std.mem.lastIndexOfScalar(u8, bytes, ')') orelse return null;+ if (end <= begin) return null;+ var fields = std.mem.tokenizeAny(u8, bytes[end + 1 ..], " \n");+ var out: Stat = .{ .name = bytes[begin + 1 .. end], .state = '?', .cpu = 0, .start = 0, .rss = 0 };+ var index: usize = 0;+ while (fields.next()) |field| : (index += 1) switch (index) {+ 0 => {+ if (field.len != 1) return null;+ out.state = field[0];+ },+ 1 => out.ppid = std.fmt.parseInt(i32, field, 10) catch return null,+ 11, 12 => out.cpu +|= std.fmt.parseInt(u64, field, 10) catch return null,+ 19 => out.start = std.fmt.parseInt(u64, field, 10) catch return null,+ 21 => {+ const rss = std.fmt.parseInt(i64, field, 10) catch return null;+ out.rss = @intCast(@max(0, rss));+ return out;+ },+ else => {},+ };+ return null;+}++pub fn parseUids(bytes: []const u8) ?Uids {+ var lines = std.mem.splitScalar(u8, bytes, '\n');+ while (lines.next()) |line| {+ if (!std.mem.startsWith(u8, line, "Uid:")) continue;+ var values = std.mem.tokenizeAny(u8, line[4..], " \t");+ var out: Uids = undefined;+ for (&out) |*uid| uid.* = std.fmt.parseInt(u32, values.next() orelse return null, 10) catch return null;+ return out;+ }+ return null;+}++pub fn parseCpu(bytes: []const u8) ?Cpu {+ var fields = std.mem.tokenizeAny(u8, bytes[0 .. std.mem.indexOfScalar(u8, bytes, '\n') orelse bytes.len], " \t");+ if (!std.mem.eql(u8, fields.next() orelse return null, "cpu")) return null;+ var out: Cpu = .{ .total = 0, .idle = 0 };+ var count: usize = 0;+ // guest and guest_nice are already included in user/nice.+ while (fields.next()) |field| : (count += 1) {+ if (count == 8) break;+ const ticks = std.fmt.parseInt(u64, field, 10) catch return null;+ out.total +|= ticks;+ if (count == 3 or count == 4) out.idle +|= ticks;+ }+ return if (count >= 4) out else null;+}++pub fn parseMemory(bytes: []const u8) ?Memory {+ var total: ?u64 = null;+ var available: ?u64 = null;+ var swap_total: ?u64 = null;+ var swap_free: ?u64 = null;+ var lines = std.mem.splitScalar(u8, bytes, '\n');+ while (lines.next()) |line| {+ var fields = std.mem.tokenizeAny(u8, line, " \t");+ const key = fields.next() orelse continue;+ const relevant = std.mem.eql(u8, key, "MemTotal:") or std.mem.eql(u8, key, "MemAvailable:") or std.mem.eql(u8, key, "SwapTotal:") or std.mem.eql(u8, key, "SwapFree:");+ if (!relevant) continue;+ const kb = std.fmt.parseInt(u64, fields.next() orelse return null, 10) catch return null;+ if (!std.mem.eql(u8, fields.next() orelse return null, "kB")) return null;+ const value = std.math.mul(u64, kb, 1024) catch return null;+ if (std.mem.eql(u8, key, "MemTotal:")) total = value;+ if (std.mem.eql(u8, key, "MemAvailable:")) available = value;+ if (std.mem.eql(u8, key, "SwapTotal:")) swap_total = value;+ if (std.mem.eql(u8, key, "SwapFree:")) swap_free = value;+ }+ return .{ .total = total orelse return null, .available = available orelse return null, .swap_total = swap_total, .swap_free = swap_free };+}++pub const Process = struct {+ dir: c_int,++ pub fn open(pid: i32) Error!Process {+ if (pid <= 0) return error.ProcessExited;+ var buf: [64]u8 = undefined;+ const path = std.fmt.bufPrintSentinel(&buf, "/proc/{d}", .{pid}, 0) catch return error.ReadFailed;+ const fd = c.open(path, c.O_DIRECTORY | c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW);+ if (fd < 0) return switch (std.posix.errno(fd)) {+ .ACCES, .PERM => error.PermissionDenied,+ .NOENT, .SRCH => error.ProcessExited,+ else => error.ReadFailed,+ };+ return .{ .dir = fd };+ }+ pub fn close(self: Process) void {+ _ = c.close(self.dir);+ }+ /// `name` points into `buf`.+ pub fn stat(self: Process, buf: []u8) Error!Stat {+ return parseStat(try readAt(self.dir, "stat", buf)) orelse error.IdentityUnavailable;+ }+ pub fn uids(self: Process, buf: []u8) Error!Uids {+ return parseUids(try readAt(self.dir, "status", buf)) orelse error.IdentityUnavailable;+ }+ /// The executable's path, possibly ending in " (deleted)".+ pub fn exePath(self: Process, buf: []u8) Error![]const u8 {+ const n = c.readlinkat(self.dir, "exe", buf.ptr, buf.len);+ if (n < 0 or n == buf.len) return error.IdentityUnavailable;+ return buf[0..@intCast(n)];+ }+};++/// The pids that exist now, in no particular order.+pub const List = struct {+ dir: *c.DIR,++ pub fn open() ?List {+ return .{ .dir = c.opendir("/proc") orelse return null };+ }+ pub fn next(self: *List) ?i32 {+ while (c.readdir(self.dir)) |entry| {+ const name = std.mem.sliceTo(entry.*.d_name[0..], 0);+ const pid = std.fmt.parseInt(i32, name, 10) catch continue;+ if (pid > 0) return pid;+ }+ return null;+ }+ pub fn close(self: *List) void {+ _ = c.closedir(self.dir);+ }+};++pub fn cpuTotals(buf: []u8) ?Cpu {+ return parseCpu(readAt(c.AT_FDCWD, "/proc/stat", buf) catch return null);+}++pub fn memoryTotals(buf: []u8) ?Memory {+ return parseMemory(readAt(c.AT_FDCWD, "/proc/meminfo", buf) catch return null);+}++/// The unit of `Stat.cpu`.+pub fn ticksPerSecond() u64 {+ return @intCast(@max(0, c.sysconf(c._SC_CLK_TCK)));+}diff --git a/src/system_monitor_tests.zig b/src/system_monitor_tests.zigindex a30e471..8afd923 100644--- a/src/system_monitor_tests.zig+++ b/src/system_monitor_tests.zig@@ -2,6 +2,7 @@ const std = @import("std");const builtin = @import("builtin");const platform = @import("platform");const proc = @import("system_monitor/proc.zig");+const linux = @import("system_monitor/proc_linux.zig");const model = @import("system_monitor/model.zig");const collector = @import("system_monitor/collector.zig");const actions = @import("system_monitor/actions.zig");@@ -13,17 +14,18 @@ fn needsProcfs() !void {}test "monitor stat parsing preserves tricky names and rejects partial data" {- const stat = proc.parseStat("123 (a ) strange\nname) S 1 2 3 4 5 6 7 8 9 10 100 50 0 0 20 0 1 0 987654 10000 42\n").?;+ const stat = linux.parseStat("123 (a ) strange\nname) S 1 2 3 4 5 6 7 8 9 10 100 50 0 0 20 0 1 0 987654 10000 42\n").?;+ try std.testing.expectEqual(@as(i32, 1), stat.ppid);try std.testing.expectEqualStrings("a ) strange\nname", stat.name);try std.testing.expectEqual(@as(u64, 150), stat.cpu);try std.testing.expectEqual(@as(u64, 987654), stat.start);try std.testing.expectEqual(@as(u64, 42), stat.rss);- try std.testing.expect(proc.parseStat("123 (gone) S 1 2") == null);- try std.testing.expect(proc.parseStat("garbage") == null);+ try std.testing.expect(linux.parseStat("123 (gone) S 1 2") == null);+ try std.testing.expect(linux.parseStat("garbage") == null);}test "monitor CPU excludes guest accounting and rejects reset counters and PID reuse" {- const before = proc.parseCpu("cpu 100 20 30 400 50 10 20 10 90 10\ncpu0 1").?;- const after = proc.parseCpu("cpu 120 20 40 440 60 10 30 20 100 10\n").?;+ const before = linux.parseCpu("cpu 100 20 30 400 50 10 20 10 90 10\ncpu0 1").?;+ const after = linux.parseCpu("cpu 120 20 40 440 60 10 30 20 100 10\n").?;try std.testing.expectEqual(@as(u64, 640), before.total);try std.testing.expectApproxEqAbs(@as(f64, 50), proc.cpuPercent(before, after).?, 0.001);try std.testing.expect(proc.cpuPercent(after, before) == null);@@ -35,11 +37,11 @@ test "monitor CPU excludes guest accounting and rejects reset counters and PID rtry std.testing.expect(proc.processPercent(first, second, 100, 1_000_000_000) == null);}test "monitor memory uses available rather than free and bounds missing values" {- const mem = proc.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 400 kB\nSwapTotal: 500 kB\nSwapFree: 250 kB\n").?;+ const mem = linux.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 400 kB\nSwapTotal: 500 kB\nSwapFree: 250 kB\n").?;try std.testing.expectEqual(@as(u64, 600 * 1024), mem.used());try std.testing.expectEqual(@as(u64, 500 * 1024), mem.swap_total.?);- try std.testing.expect(proc.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\n") == null);- try std.testing.expect(proc.parseMemory("MemTotal: 18446744073709551615 kB\nMemAvailable: 1 kB") == null);+ try std.testing.expect(linux.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\n") == null);+ try std.testing.expect(linux.parseMemory("MemTotal: 18446744073709551615 kB\nMemAvailable: 1 kB") == null);}fn fixture(pid: i32, start: u64, name: []const u8, uid: u32, cpu: f64) collector.Process {return .{ .identity = .{ .pid = pid, .start = start }, .name = name, .user = "alex", .uids = .{ uid, uid, uid, uid }, .state = 'S', .cpu_ticks = 0, .cpu_percent = cpu, .resident_bytes = 4096, .protected = false };