Skip to content

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

freebsd fixes

oxydizer3184e2ac6c20
diff --git a/AGENTS.md b/AGENTS.md
index b10ce62..650d188 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -221,7 +221,8 @@ panel painting. The key rules:
re-check). Synthetic input and pixel reads need `[ipc] automation`. Socket
only in a private directory, umask 0177. Sandboxed callers need an explicit
`[[sandbox_allow]]` `ipc` allowance, fail closed and are re-checked on
- reload. `scroll` is natural by default (negative dy pages down).
+ reload; a connector that has exited or whose pid is not visible is refused
+ (a child may hold its socket). `scroll` is natural by default (negative dy pages down).
* **Security context** (`global_filter.zig`) hides privileged globals from
`wp_security_context_v1` clients (guess-binds are protocol errors) unless
`[[sandbox_allow]]` grants the group; nested contexts are fatal.
diff --git a/build/tests.zig b/build/tests.zig
index 2ef0710..316ad4f 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -203,6 +203,8 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
});
polkit_service.root_module.addImport("wayland", wayland);
polkit_service.root_module.addImport("i18n", i18n_mod);
+ polkit_service.root_module.addImport("c", ctx.c.libc);
+ polkit_service.root_module.addImport("platform", ctx.platform_mod);
polkit_service.root_module.linkSystemLibrary("wayland-server", .{});
polkit_service.root_module.addCSourceFile(.{ .file = b.path("src/polkit/native.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
polkit_service.root_module.linkSystemLibrary("pthread", .{});
diff --git a/docs/freebsd-build.md b/docs/freebsd-build.md
new file mode 100644
index 0000000..c981c45
--- /dev/null
+++ b/docs/freebsd-build.md
@@ -0,0 +1,91 @@
+# Building RediWM on FreeBSD
+
+Experimental: FreeBSD 15.x only (D1 in [the plan](plans/freebsd.md)), amd64.
+The tree builds and the unit tests pass; the compositor needs a DRM render
+node to start, so a VM without a GPU stops at renderer initialisation. Which
+features work is in the plan.
+
+## Packages
+
+These are the packages' names. Each was checked against the FreeBSD 15.1
+`latest` catalogue on 2026-11-06 and exists. To check again (`pkg search -e`
+compares the name with its version, so it finds nothing here; `pkg rquery`
+compares the name alone):
+
+ for p in wayland wayland-protocols wlroots020 libxkbcommon cups pixman \
+ freetype2 harfbuzz fontconfig cairo pango librsvg2-rust gdk-pixbuf2 \
+ glib webp libarchive libinput libudev-devd png jpeg-turbo pulseaudio \
+ pipewire libxcb poppler-glib readline libglvnd mesa-dri libdrm \
+ pkgconf python3 py312-pillow seatd dbus xwayland dejavu; do
+ [ -n "$(pkg rquery -x '%n' "^$p\$")" ] && echo "ok $p" || echo "MISSING $p"
+ done
+
+What each is for:
+
+* **Toolchain:** Zig 0.17, `pkgconf`, a C and C++ compiler (base clang),
+ `python3` and `py312-pillow` for the integration tests (they import PIL;
+ without it every one of them fails on its first line).
+* **Graphics stack:** `wlroots020` (0.20 exactly; it pulls in most of this
+ stack, but list it all), `wayland` (client, server, cursor and
+ `wayland-scanner`), `wayland-protocols`, `libxkbcommon`, `pixman`,
+ `libglvnd` and `mesa-dri` (EGL, GLESv2), `libxcb`.
+* **Drawing and files:** `cairo`, `pango`, `freetype2`, `harfbuzz`,
+ `fontconfig`, `librsvg2-rust`, `gdk-pixbuf2`, `glib` (gio and gobject),
+ `png`, `jpeg-turbo`, `webp`, `libarchive`, `poppler-glib` (the PDF viewer),
+ `readline` (the Files terminal's shell hook).
+* **Services the compositor talks to:** `cups`, `pulseaudio` (libpulse),
+ `pipewire` (the bass boost; it is linked, not optional). PAM is the base
+ system's OpenPAM, `libutil` and `libm` are base too.
+* **To run a session:** `seatd` (running, the user in its group), `dbus`,
+ `xwayland`, a GPU driver (`drm-kmod` and its firmware package) and a
+ monospace font for the editor tests (`dejavu`). The login stack is probed
+ with `tools/freebsd-probe/login-probe.sh`.
+* **Only with `-Dtransfers`** (off on FreeBSD): `libtorrent-rasterbar2`,
+ `json-glib`.
+
+## Build
+
+ zig build # Debug (LLVM backend by default)
+ zig build -Doptimize=ReleaseSafe
+ zig build test
+
+Off by default on FreeBSD: the transfers helper (`-Dtransfers`) and
+`rediwm-session`/`rediwm-dm` (`-Dlogin-session`). The install prefix is
+`/usr/local`, configuration `/usr/local/etc` and run state `/var/run`
+(`-Dinstall-prefix`, `-Dsysconfdir`, `-Drundir`).
+
+## Tests
+
+`zig build test` runs the unit tests and the other `test-*` steps single
+areas. On FreeBSD 15.1 without a GPU (2026-11-06) these pass: `test`,
+`test-monitor`, `test-platform`, `test-polkit`, `test-dbus` (its part that
+drives the bus with `busctl`, systemd's tool, skips), `test-files`,
+`test-i18n`, `test-wlroots`, `test-lock`, `test-editor`, `test-images`,
+`test-pdf`, `test-lifecycle`, `test-node`, `test-projection`, `test-glass`,
+`test-gpu-timing` and `test-switcher-preview`. Skips on FreeBSD are on
+purpose: the German and Russian name-order tests (libc's order differs from
+glibc's) and the folder-size test that counts `/proc/self/fd`.
+
+Everything that starts the compositor needs a DRM render node
+(`/dev/dri/renderD128`, `WLR_RENDER_DRM_DEVICE` pointing at it) and fails
+without one with `No rediwm-*.sock found`: `test-power`,
+`test-power-profiles`, `test-tray`, `test-notifications`, `test-file-chooser`,
+`test-settings-portal`, `test-app-activation`, `test-layout-autosave`,
+`test-printers`, `test-files-terminal` and the `tests/*.py` suites. The
+Python tests import PIL (`py312-pillow`), and some compile C clients with
+plain `cc`: export `CPATH=/usr/local/include LIBRARY_PATH=/usr/local/lib`.
+A qemu guest has a render node only with a virtio GPU:
+`-device virtio-vga-gl -display sdl,gl=on`, and `virtio_gpu_drm` in
+`kld_list`. With that, the headless compositor runs GLES2 on
+`/dev/dri/renderD128` (Mesa's virgl driver).
+
+Run the suites one at a time, each in its own scratch `HOME` and `XDG_*`
+directories, and do not wrap them in `timeout(1)`: on FreeBSD it can keep
+waiting after its child has exited, so a suite that passed reports a timeout.
+A loop that polls `kill -0` and kills at a limit works. Tools some suites
+need besides the packages above: `squashfs-tools` (`files_associations`),
+`xdpyinfo` (`xwayland*`), `wlr-randr`, `py312-libtorrent-rasterbar`
+(`files_torrents`). Several suites are Linux only: `system_monitor` (a seccomp
+guard and `/proc`), `motion_perf` and `editor_visuals` (`/proc`),
+`battery_*` and `pdf_sandbox` (Linux hook libraries), `steamos_bundle`,
+and those that need `rediwm-session` or `rediwm-dm`.
diff --git a/docs/plans/freebsd.md b/docs/plans/freebsd.md
index 2116a7b..2d4b038 100644
--- a/docs/plans/freebsd.md
+++ b/docs/plans/freebsd.md
@@ -1,250 +1,231 @@
# FreeBSD support plan
-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 and
-the whole tree cross-compiles for `x86_64-freebsd` (Debug, ReleaseSafe, tests;
-see Validation). The third outside build (fa55c2a, FreeBSD 15.1 VM without a DRM
-render device) builds Debug and ReleaseSafe and passes the platform tests, but
-the compositor stops at renderer initialisation, so only unit tests have run.
-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
-stays the primary platform; the port must not change Linux behaviour or cost.
-
-## Where we stand
-
-The graphics stack is portable. wlroots supports FreeBSD (libseat + seatd,
-drm-kmod, libinput, libudev-devd), and Mesa, Xwayland, cairo, freetype,
-harfbuzz, fontconfig, librsvg, gio, CUPS, libarchive, D-Bus, polkit,
-xdg-desktop-portal, pulseaudio and OpenPAM are in ports. Zig 0.17 targets
-`x86_64-freebsd`. Night light rides wlroots' DRM gamma and should port as is.
-
-Our own code had no OS abstraction. It now lives in `src/platform/` (child
-handles, file watching, own path, peer credentials, process attributes, wake
-descriptors, rename and stat, seccomp filters, tool lookup, with C headers
-beside it), with a FreeBSD half for each part except seccomp. About 15 files
-still use `std.os.linux` outside it (the supervisor, the DM, the Files
-folder-size walk, `Output.zig`, the seccomp policy tables). What is left is
-the Linux-only interfaces below, sandboxes, services and the login manager.
-
-A first outside build (FreeBSD 15.1-RELEASE amd64, AMD Navi 44 on drm-kmod,
-Zig 0.17.1, wlroots 0.20 from ports `x11-toolkits/wlroots020`) built 72 of 114
-steps. Every failure was a known item or a missing package and was fixed on the
-Linux side (P.8–P.10; the transfers helper is off by default on FreeBSD).
-The second build of the same tester (14 failed of 106 Debug steps) stopped at
-the parts that P.4 and P.9 had deliberately made refuse to build off Linux,
-plus what that exposed: `c.SIG_IGN` does not translate, glibc's socket-address
-union, 16-bit `mode_t`, `landlock.h`, `pty.h`, `MADV_DONTDUMP`, `pam_start_confdir`,
-`_NL_*` locale items, `CLOCK_BOOTTIME`, netlink uevents, `renameat2` and
-`statx`, xattr calls, and the D-Bus control-message data offset (FreeBSD's
-`cmsghdr` is 12 bytes, its data starts at 16). All are fixed except what the
-next paragraph lists.
-On 15.1 `sys/inotify.h`, `sys/timerfd.h`, `sys/eventfd.h` and `cr_pid` in
-`sys/ucred.h` exist (header checks only). The platform tests now pass on 15.1, among them kqueue child
-exits and reaping, watchers and the `cr_pid` of a unix-socket peer. Not known
-yet: `memfd_create`, the transfers helper's C++ flags under clang and libc++,
-whether the kqueue child handles behave in the Wayland loop (libepoll-shim),
-and whether a DRM session or the headless GLES2 path works: wlroots'
-renderer needs a DRM render node (`drmGetDevices2 failed`), which the qemu VM
-lacks, so `rediwm-msg` and the Files lifecycle are untested. The second tester log also showed a Debug `rediwm-cursorgen` dying with
-`Undefined symbol "environ"` while its ReleaseSafe build ran, so the build now
-defaults to LLVM on FreeBSD; confirm it. Two tests failed at run time: the
-D-Bus fd test (fixed, the offset above) and the images decoder test (probably
-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 Linux
-syscalls; now libc), the polkit helper's backpressure test (its fill loop
-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
+Status: 2026-11-06, FreeBSD 15.1 only (D1). The tree builds there and the
+compositor and apps run headless on GLES2 over a virtio GPU. What is left is
+the login and session stack, the Linux-only interfaces, sandboxes, a few
+FreeBSD-only test failures and packaging. D1–D5 are decided, D6 waits for
+phase 2, D7–D9 are recommendations.
+
+Goal: run RediWM on FreeBSD: the compositor in a seatd session on DRM, then the
+shell features and apps, last `rediwm-dm` and packaging. Linux stays the
+primary platform; the port must not change Linux behaviour or cost.
+
+## Done
+
+* **Code:** `src/platform/` owns the OS calls (child handles, file and
+ directory watching, own path, peer credentials, process attributes, wake
+ descriptors, rename and stat, `kern.proc` process list, tool lookup), each
+ with a FreeBSD half except seccomp. The Linux-side preparation (P.1–P.4,
+ P.6–P.10) is finished. The IPC allowance check refuses a connector that has
+ exited or cannot be seen.
+* **On 15.1** (HyprBSD VM, Zig 0.17.1): Debug builds in 2.5 minutes,
+ ReleaseSafe in 6.7. `zig build test` passes, and so do `test-monitor` (the
+ `kern.proc` backend and kqueue End/Force), `test-platform`, `test-files`,
+ `test-dbus`, `test-polkit` and the other no-GPU steps. With a render node
+ the Python suites mostly pass (`ipc_automation`, `lock_screen`, `greeter`,
+ `files_browser`, `images_viewer`, `editor`, `launch_placeholder`,
+ `focus_zoom`, `window_snapping`, most appearance, undo, window-rule and
+ protocol suites). Kqueue child handles work in the Wayland loop.
+* **Found by running there and fixed:** synthetic input stamped with clock id
+ 1 (`CLOCK_VIRTUAL` on FreeBSD); Files' `rm --interactive=never`; a Control
+ Center crash on a zoomed camera (also on Linux); tests naming `/bin/true`,
+ using GCC-16-only C, `SO_PEERCRED`, `setsid --ctty`, `busctl`; `test-polkit`
+ not building on Linux at HEAD.
+* **Tools:** `tools/freebsd-cross/check.sh` cross-builds the tree from Linux;
+ `tools/freebsd-probe/login-probe.sh` reports the login stack;
+ `docs/freebsd-build.md` has the package list (checked against the 15.1
+ catalogue), build commands and how to run the tests.
+
+## Still failing or unknown on FreeBSD
+
+* Pixel-comparison suites `start_menu`, `zoom_osd`, `screenshot_tool` and `dock`
+ pass on Linux and fail on the VM (virgl against the host's renderer is the
+ suspect; not looked into). `theme_packs` fails because the parser sandbox
+ refuses (D4). `system_monitor.py` is Linux only (seccomp guard, `/proc`) and
+ needs a FreeBSD variant; `motion_perf`, `editor_visuals`, `battery_*`,
+ `pdf_sandbox` and `steamos_bundle` are Linux only too. The other failures
+ also fail on Linux at HEAD.
+* Not tried: a DRM session on real or virtual hardware, a nested session under
+ Hyprland, `rediwm-msg` outside the tests, `memfd_create`, the transfers
+ helper's C++ flags under clang and libc++.
+* Name order follows FreeBSD's libc (`de_DE` is a link to `en_US`, Cyrillic has
+ no usable weights); the German and Russian order tests skip off Linux (D7).
+
+## Interfaces still to port
| Linux interface | Where | FreeBSD |
| --- | --- | --- |
-| pidfd (`platform.child` `Handle`, `Set`; `child.h`). **Zig side done** (`child_freebsd.zig`); `child.h` is Linux only and the terminal that uses it refuses to start | `session/child`, supervisor, dm, IPC, `Toplevel`, pickers, System Monitor, terminal engine | kqueue `EVFILT_PROC`/`NOTE_EXIT`, its fd joining the wl loop like a pidfd. Signals by pid, guarded by the unreaped zombie, which holds only for our own children: handles on other processes (`Toplevel` client pids, IPC peers, System Monitor) need another identity check (start time from `kern.proc`). `Handle.pid()` (fdinfo) has no counterpart. |
-| `signalfd`, `epoll` | supervisor, dm, `child.Set` | kqueue `EVFILT_SIGNAL`, kqueue. |
-| `inotify` (`platform.watch`) | 7 users | Native on 15 (**done**, libc); on 14.x kqueue `EVFILT_VNODE` has no names, so diff the directory. |
-| `eventfd` (`platform.wake`) | 9 sites | Native (13+); the flag values differ (**done**). |
-| `memfd_create`, `timerfd` | few | `sys/timerfd.h` on 15.1; confirm `memfd_create` in phase 0. |
-| `prctl` (`platform.process`, `process.h`) | dm worker, lock, PAM worker, PDF, theme helper, supervisor subreaper | `procctl` (`PROC_PDEATHSIG_CTL`, `PROC_NO_NEW_PRIVS_CTL`, `PROC_TRACE_CTL`, `PROC_REAP_ACQUIRE`), `pthread_set_name_np` (**done**). |
-| `SO_PEERCRED` (`platform.peer`, `peer.h`) | IPC (uid and pid, for sandbox allowances), `session_restart`, `files/torrents`, torrent helper, `bash.c` | `getsockopt(LOCAL_PEERCRED)` into `struct xucred` (**done**; a peer with `cr_pid` 0 is refused). Check at run time that `cr_pid` is filled for a unix-socket peer. `files/terminal/engine.c` authenticates each shell message with `SCM_CREDENTIALS`; FreeBSD's `SCM_CREDS` is sender-attached, so `bash.c` would send it too: decide when the port reaches the terminal. |
-| `/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 | 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). |
-| netlink `KOBJECT_UEVENT` | printer hotplug (`printing/client.zig`) | devd's seqpacket socket, or rescans only (rescans only, **done**). |
-| `gettid`; `fork`, `kill`, `wait4`, `poll` loops | `thumbs`; supervisor and dm | A `platform` wrapper; the loops are replaced in phases 2 and 4. |
-
-### Sandboxes
-
-The PDF sandbox (`pdf/sandbox.c` + `pdf/syscall_policy.zig`: raw BPF through
-`platform/seccomp.zig`, + Landlock) and the theme helper
-(`theme_helper/native.c` + `syscall_policy.zig`: the same builder, + Landlock)
-have no FreeBSD counterpart short of a rewrite on **Capsicum** (`cap_enter`,
-`cap_rights_limit` on pre-opened directory fds). The design fits, since both
-already preload before the sandbox closes (`compose.preload`), but capability
-mode forbids every path-based `open`, so fontconfig and late lookups need an
-audit. Until then both helpers refuse to run on FreeBSD: sandboxing fails
-closed (`rediwm_pdf_sandbox_enter` and the theme helper's `parser_sandbox`
-return `ENOTSUP` there; the PDF viewer opens nothing and theme packs cannot be
-imported).
-
-### System services
+| pidfd in `child.h` (the C side) | terminal engine, supervisor, dm | kqueue `EVFILT_PROC`/`NOTE_EXIT` like the Zig side. Handles on other processes (client pids, IPC peers, monitor) need an identity check (start time from `kern.proc`; the monitor's actions already do); `Handle.pid()` (fdinfo) has no counterpart. |
+| `signalfd`, `epoll` | supervisor, dm | kqueue `EVFILT_SIGNAL`, kqueue. |
+| `/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, per site. |
+| `pty.h`, `SCM_CREDENTIALS`, `/proc` walks | Files terminal engine | `ft_start` refuses on FreeBSD. Port the per-message check (`SCM_CREDS` is sender-attached, so `bash.c` would send it) and the session teardown walk (`kern.proc` by session); needs a FreeBSD to test on. |
+| `/proc/<pid>` leftovers | `detectSandbox` (no Flatpak: "not sandboxed"), editor memory probe, `session_restart` (Linux install tool), supervisor teardown tree | A failed read means "not sandboxed" or no check; the supervisor's walk is phase 2. |
+| `DRM_IOCTL_VERSION` | `Output.zig` | `drmGetVersion`; skipped on FreeBSD (a hypervisor-GPU workaround only). |
+| netlink `KOBJECT_UEVENT` | printer hotplug | devd's seqpacket socket; rescans only today. |
+| `gettid`; `fork`/`kill`/`wait4`/`poll` loops | `thumbs`; supervisor and dm | A `platform` wrapper; the loops are replaced in phases 2 and 4. |
+| `RENAME_EXCHANGE`, `renameat2` | theme helper, transfers helper | Linux only. |
+
+Done and not repeated: the Zig side of pidfd, inotify, eventfd, `prctl`,
+`SO_PEERCRED`, `/proc/self/exe`, `statx`/`getdents` (Files folder sizes),
+`renameat2` at the Zig sites, the process list. Its limits: no swap figures,
+`ki_comm` names are 19 characters, and the exe path is read by pid.
+
+## Sandboxes
+
+The PDF sandbox and the theme helper use raw BPF through `platform/seccomp.zig`
+plus Landlock; FreeBSD needs a rewrite on **Capsicum** (`cap_enter`,
+`cap_rights_limit` on pre-opened directory fds). Both already preload before
+the sandbox closes, but capability mode forbids every path-based `open`, so
+fontconfig and late lookups need an audit. Until then both refuse to run
+(`ENOTSUP`): the PDF viewer opens nothing and theme packs cannot be imported
+(D4). FreeBSD recognises no sandboxed IPC peer, so a Capsicum child must never
+be handed the IPC socket. Unchecked: whether a Flatpak app with `--allow=devel`
+can overmount `/.flatpak-info` in its own mount namespace.
+
+## System services
| Feature | Linux | FreeBSD |
| --- | --- | --- |
-| Power, suspend, lock-before-sleep inhibitor, logind `Lock`, polkit agent session | logind (`session/login_bus`, `power*`, `polkit/agent`) | ConsoleKit2 (`org.freedesktop.ConsoleKit`: PowerOff/Reboot/Suspend/Inhibit) as a third backend beside systemctl/loginctl in `power.zig`. |
-| App scopes, activation environment | systemd1 | Already degrades ("no systemd user manager"). |
-| Battery | `/sys/class/power_supply` + uevents | `hw.acpi.battery.*`, devd ACAD/CMBAT notifications. Keep "only on events and the minute tick". |
+| Power, suspend, lock-before-sleep inhibitor, `Lock`, polkit agent session | logind (`session/login_bus`, `power*`, `polkit/agent`) | ConsoleKit2 behind the login-manager interface (P.11, D5). |
+| Battery | `/sys/class/power_supply` + uevents | `hw.acpi.battery.*`, devd ACAD/CMBAT; keep "only on events and the minute tick". |
| Brightness | `brightnessctl` | `backlight(8)`. |
-| Wi-Fi, Ethernet | NetworkManager | Absent. Hidden (D3). |
-| Bluetooth | BlueZ | Absent. Hidden. |
-| Files DEVICES | UDisks2 | `sysutils/bsdisks` implements a UDisks2 subset; qualify, hide what fails. |
-| Power profiles | power-profiles-daemon | Absent (`powerd`). Hidden. |
-| Accounts | `useradd`/`usermod`/`userdel`/`chpasswd`/`gpasswd`/`loginctl` | `pw(8)`; password through `pw usermod -h 0`. |
-| Audio | libpulse; PipeWire for the bass DSP | pulseaudio or pipewire-pulse; the DSP is optional. |
+| Files DEVICES | UDisks2 | `sysutils/bsdisks` implements a subset; qualify, hide what fails. |
+| Accounts | `useradd`, `usermod`, `chpasswd`, `gpasswd`, `loginctl` | `pw(8)`; password through `pw usermod -h 0`. |
+| Wi-Fi, Ethernet, Bluetooth, power profiles, app scopes | NetworkManager, BlueZ, PPD, systemd1 | Absent and hidden (D3). |
-### rediwm-dm
+## rediwm-dm
The most Linux-bound program: `pam_systemd` registration, Linux VT ioctls on
-`/dev/tty0`/`/dev/ttyN` (FreeBSD: `/dev/ttyv*`, `sys/consio.h`, different
-numbers), PDEATHSIG, signalfd, pidfd. On FreeBSD `XDG_RUNTIME_DIR` comes from
-`pam_xdg` and device access from a running seatd. The DM is optional and never
-enabled by the installer, so the port ships without it first (D2): start from
-the console through seatd, or from greetd.
-
-### Build and install
+`/dev/tty0`/`ttyN` (FreeBSD: `/dev/ttyv*`, `sys/consio.h`), PDEATHSIG,
+signalfd, pidfd. On FreeBSD `XDG_RUNTIME_DIR` comes from `pam_xdg` and device
+access from a running seatd. It is optional and the port ships without it first
+(D2).
+
+## Login and seat
+
+**Seat** is wlroots': libseat with seatd, the user in its group, drm-kmod,
+libinput on libudev-devd. To check on real hardware: VT switching under
+`vt(4)`, and typing in the compositor must not also reach the console tty.
+
+**Login identity** is ours. `REDIWM_LOGIN_SESSION`, set by `rediwm-session`
+after logind confirms the login (`login_bus.zig`: Type=wayland, Class=user,
+Desktop=rediwm, not remote, same uid), gates the polkit agent, the activation
+environment, following `Lock` and keeping `LockedHint`, and the Files terminal.
+Left to do:
+
+* One login-manager interface (P.11): logind implementation (today's code,
+ moved) and a ConsoleKit2 one: session of a pid, `Lock` signal,
+ `SetLockedHint`, sleep and lid inhibitors with `PrepareForSleep`, capability
+ probes, power calls. Today logind's names are constants in `power.zig`
+ imported by `power_*`, and `login_bus.zig` and `polkit/agent.zig` spell them
+ out.
+* A ConsoleKit2 check (D8): local, our uid, Type=wayland, not remote, from a
+ session `rediwm-session` opens itself. No Desktop property, and a session
+ without a display device is never active, so "active" cannot be required.
+
+**Session environment.** `XDG_RUNTIME_DIR` comes from `pam_xdg` (HyprBSD puts
+it in `/etc/pam.d/system`, which `login` and the DM include and `sshd` does
+not). Socket paths must fit `sun_path`'s 103 characters. Nothing starts the
+session bus: `rediwm-session` starts `dbus-daemon --session` when nothing
+listens, or the start script wraps it in `dbus-run-session`. `dbus`, `seatd`,
+ConsoleKit2 and polkitd must be enabled.
+
+**Supervisor.** `rediwm-session` is Linux only (pidfd, signalfd, subreaper,
+`std.os.linux`) and not built on FreeBSD. "A crash never unlocks" relies on it
+restarting the compositor locked, so its port (phase 2) comes before FreeBSD
+claims a lock. Until then, `exec` the session from the login shell (D9).
+
+**What the probe showed** (HyprBSD VM, ConsoleKit2 2.0.0, seatd 0.9.3, polkit
+128, over ssh and under `ck-launch-session`):
+
+* No PAM stack opens a ConsoleKit2 session (no `pam_ck_connector`), so a
+ console login has none (inferred, not run on a console). `ck-launch-session`
+ or D-Bus `OpenSessionWithParameters` (allowed to users) creates one;
+ `GetSessionForUnixProcess` and `GetCurrentSession` then find it from a
+ descendant.
+* `OpenSessionWithParameters` honours `session-type` (`wayland`, `tty`) and
+ `remote-host-name`, ignores unknown names, and `is-local=false` did not
+ change `IsLocal`. A session without a display device gets its own seat, is
+ never active and has VT 0. Any process of the user can open one of any type,
+ so the identity is a same-uid assertion where logind's is made by PAM.
+* Manager has `GetSessionForCookie`, `OpenSession`, `CloseSession`, `Inhibit`,
+ `ListInhibitors`, `PrepareForSleep`/`PrepareForShutdown` and the power calls
+ with `Can…`. Session has type, class, uid, `IsLocal`, `IsActive`,
+ remote host, `GetXDGRuntimeDir`, `GetVTNr`, `SetLockedHint`, `SetIdleHint`,
+ `Lock`/`Unlock` signals, `TakeControl`, `TakeDevice`; no Desktop and no
+ locked-hint getter.
+* seatd runs as `seatd -g video`, socket `/var/run/seatd.sock` (root:video,
+ 0770); clients use `LIBSEAT_BACKEND=seatd`.
+* polkit answers `auth_admin` for the ssh shell and the session's shell alike;
+ whether it needs an active or ConsoleKit2-owned session is not settled.
+* The VM's own `/usr/local/libexec/hyprbsd/session` is a working template:
+ checks `XDG_RUNTIME_DIR`, `/dev/dri/card*` and the `video` group, runs under
+ `ck-launch-session`, finds its id with `GetSessionForCookie`, then
+ `exec dbus-run-session -- start-hyprland`.
+
+## Build and install
`scripts/install-session-root.sh` and `scripts/make-deb.sh` are Linux
installers (GNU `install -D`, systemd units, Debian/Arch PAM files); FreeBSD's
-`install -D` means DESTDIR, so it gets its own `pkg` path in phase 4. The
-transfers helper's `c++ -Werror … -D_GLIBCXX_ASSERTIONS` line is unchecked
-under clang and libc++ until the helper is enabled there.
+`install -D` means DESTDIR, so it gets its own `pkg` path in phase 4.
## Rules for the port
-* **One platform module.** `src/platform/` (named module, no compositor
- imports) owns child watching, signal sources, file watching, process control
- and attributes, own-executable path, peer credentials, wake descriptors and
- process listing, with `linux_*.zig` and `freebsd_*.zig` parts chosen at
- comptime. Callers never test the OS themselves; `std.os.linux` is used only
- inside it. Parts not yet ported refuse to build for another OS.
-* **One translate root, OS conditions inside.** `src/c/libc.h` lists the
- portable headers; those that exist on one OS only sit under `#ifdef
- __linux__` (later `__FreeBSD__`) at its end, so Zig code that needs a
- Linux-only name fails at its use, not at the translation.
+* **One platform module.** `src/platform/` (no compositor imports) owns the OS
+ calls, with `linux_*.zig` and `freebsd_*.zig` parts chosen at comptime.
+ Callers never test the OS; `std.os.linux` is used only inside it. Parts not
+ ported refuse to build for another OS.
+* **One translate root.** `src/c/libc.h` lists the portable headers; one-OS
+ headers sit under `#ifdef __linux__` or `__FreeBSD__` at its end.
* **Missing services hide, never fake.** A feature without a backend is absent
- from the taskbar and Settings, as on a Linux machine lacking it.
+ from the taskbar and Settings.
* **Fail closed.** No sandbox, no sandboxed app; no peer pid, no IPC allowance.
-* **Keep wlroots' portable layers.** Session, backend, DRM, libinput and udev
- handling stay in wlroots. Any future replacement of them with our own code
- goes through `platform` with both implementations from day one.
-* Security rules from the root `AGENTS.md` apply unchanged (greeter, lock, no
- test hooks in production, mlocked secrets).
-
-## Phases
-
-### P. Preparation on Linux (before any FreeBSD work)
-
-Each step keeps behaviour and was checked with Debug, ReleaseSafe,
-`zig build test` and the affected suites against HEAD.
-
-Done:
-
-1. `platform.child` (`Handle`, `Set`, `reap`, `killAndReap`) replaced the ad
- hoc pidfd sites; `Pid` and `Signal` are `std.posix` types.
-2. `platform.watch.Watcher` for the 7 inotify users.
-3. `platform.exe` and `self_exe.h` for the `/proc/self/exe` readers.
-4. Plain calls use libc or `std.posix`; `platform.process`/`process.h` take the
- `prctl` calls and `platform.wake` the `eventfd` pairs. Left on
- `std.os.linux`: the supervisor and dm, the table's Linux-only calls, the
- 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. `-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
- FreeBSD headers translate it (see Validation). Code using the moved names
- (`dm/worker`, `session/lock`, `printing/client`, and four C files that
- include `sys/prctl.h`) now fails for FreeBSD at its use.
-
-Open:
+* **Keep wlroots' portable layers** (session, backend, DRM, libinput, udev).
+* Security rules from the root `AGENTS.md` apply unchanged.
+
+## Remaining work
+
+### P. Linux-side preparation (open)
5. **One sandbox interface:** give the PDF sandbox and the theme helper one
"restrict to these directories" entry point, which Capsicum later
implements. Their Landlock code differs on purpose (PDF: read-only trees,
ABI 3 required, fails closed; theme helper: optionally writable root and
`/usr` executable, runs without Landlock on older kernels), so settle what
- it promises before moving either. Security work: needs its own review.
+ it promises first. Security work: needs its own review.
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)
-
-FreeBSD 15 VM with drm-kmod and seatd. Build wlroots 0.20 and dependencies,
-run the headless backend, a nested session and a DRM session with an upstream
-example compositor. Record which of the "native, confirm" interfaces exist on
-the target release(s) (D1), and whether the integration tests' headless +
-GLES2 path works there.
-
-### 1. Compositor builds and runs
-
-`src/platform/` has its FreeBSD parts and the tree cross-compiles; what
-is left is to run it. `rediwm-session` and `rediwm-dm` are not built on
-FreeBSD (`-Dlogin-session`, default off there) until phases 2 and 4. Hide NM,
-BlueZ, PPD, UDisks, app scopes; PDF and theme helper refuse (done); the
-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 stopped
-on a missing `libtorrent-rasterbar`). Goal: `rediwm` and the apps start in a
-seatd session and the headless integration suites run.
+ `/usr/local/sbin`; the accounts helper's candidate lists need `pw(8)`
+ (phase 3). Phase 2 decides `/run/polkit/agent-helper.socket` (systemd's
+ helper socket; the agent could start the setuid helper itself via
+ `rediwm_polkit_spawn`). `/etc/pam.d` and `/run/rediwm-dm` are written by the
+ Linux installers only. Kept on purpose: `/etc/xdg`, `/etc/login.defs`.
+11. **Login-manager interface:** move the logind calls of `login_bus`,
+ `polkit/agent` and `power_*` behind one interface, the logind implementation
+ unchanged and a recording fake for tests (`tests/power.py`, `polkit.py`,
+ `rediwm_session.py`, `session_bus.py` as the check). The ConsoleKit2
+ implementation is phase 2.
+
+### 1. Compositor runs (finish)
+
+Headless works. Left: a DRM session on the VM's virtio GPU or real hardware, a
+nested session under Hyprland, the four pixel suites above, `memfd_create`,
+the transfers helper if wanted. `rediwm-session` and `rediwm-dm` stay off
+(`-Dlogin-session`, default off there) until phases 2 and 4. Goal: `rediwm`
+and the apps start in a seatd session.
### 2. Real session
-ConsoleKit2 power, suspend and inhibitor; lock follows ConsoleKit's `Lock`;
-battery and brightness backends; peer credentials for IPC; `rediwm-session`
-supervisor on kqueue. Goal: daily-usable session started from the console.
+The ConsoleKit2 login-manager implementation (`rediwm-session` opens the
+session; identity, power, suspend, inhibitor; lock follows `Lock`); `pam_xdg`
+and the session bus; battery and brightness backends; `rediwm-session`
+supervisor on kqueue. Goal: a daily-usable session started from the console.
### 3. Parity
-Capsicum sandboxes for PDF and the theme helper; system monitor collector on
-libprocstat; accounts helper on `pw`; printer hotplug via devd; bsdisks
-qualification for Files DEVICES.
+Capsicum sandboxes for the PDF viewer and theme helper; the System Monitor's
+swap figures and long command names (`vm.swap_info`, `KERN_PROC_ARGS`);
+accounts helper on `pw`; printer hotplug via devd; bsdisks for Files DEVICES;
+the Files terminal.
### 4. Login manager and packaging
@@ -253,48 +234,33 @@ release tarball or a port (D6); FreeBSD in `make-release.sh` verification.
## Decisions
-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).
+* **D1 Target release: 15.x only** (D1–D5 made 2026-11-05). Native inotify and
+ timerfd; 14.x would need kqueue vnode watching.
* **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.
+* **D3 Network: hide** the NetworkManager and BlueZ items; a wpa_supplicant
+ backend may follow.
+* **D4 Sandboxed apps before Capsicum: refuse** (implemented: `ENOTSUP`).
+* **D5 Power backend: ConsoleKit2**, not our own polkit-gated helper.
+* **D6 Distribution:** prebuilt tarball like Linux, or a port in `x11-wm`.
+ Decide after phase 2.
+* **D7 Name collation:** accept FreeBSD libc's order (done) or ship our own for
+ Latin and Cyrillic. Recommend accept until a user asks.
+* **D8 Login check on FreeBSD:** `rediwm-session` opens the ConsoleKit2 session
+ itself (Type=wayland), so the logind check's shape stays minus Desktop and a
+ console login needs no relaxation. It proves a process of this user
+ registered a session, not that PAM did. Recommended.
+* **D9 First start path:** `rediwm-session` from a console login (profile or a
+ small start script), not greetd; the lock's crash guarantee rests on it.
+ Recommended.
## Validation
Each phase: Linux Debug and ReleaseSafe builds, `zig build test` and the
-affected integration suites, compared against HEAD in a worktree; the same on
-FreeBSD from phase 1, starting with the headless suites. `strings` a
+affected suites against HEAD in a worktree; the same on FreeBSD (see
+`docs/freebsd-build.md` for the VM setup, the watchdog runner and the tools the
+suites need). `tools/freebsd-cross/check.sh` after touching OS interfaces, C
+headers or `src/platform/`: it proves compilation only, and the `undefined
+symbol`s it leaves should be checked for names libc owns. `strings` a
ReleaseSafe `rediwm` on both after touching environment handling. Sandbox work
-(P.5, phase 3) gets a dedicated escape test per helper: path opens, sockets
-and exec are denied.
-
-A FreeBSD translation of `src/c/libc.h` can be checked on Linux with Zig's
-bundled FreeBSD headers. `zig translate-c` adds the host's `/usr/include`
-whatever the target, so hide it, and give Zig private caches:
-
- bwrap --ro-bind / / --tmpfs /usr/include --tmpfs /usr/local/include \
- --bind SCRATCH SCRATCH --bind SCRATCH/zglobal ~/.cache/zig \
- --bind SCRATCH/zlocal ./.zig-cache --dev /dev --proc /proc \
- zig translate-c -target x86_64-freebsd -lc src/c/libc.h
-
-On a root that still includes `linux/netlink.h` it fails with the outside
-tester's error. It covers `libc.h` only: the roots that need cairo, libinput or
-wlroots headers need FreeBSD's own, and Zig's headers may be older than 15.1.
-
-The whole build can be cross-checked the same way, to catch the next layer of
-errors before the tester does (Zig reports errors only in code it reaches, so
-fixes expose more): `tools/freebsd-cross/check.sh` (see its README). A pass
-means every unit compiled and the build reached the link; it cannot show
-header-version differences, library versions or anything that runs. The only
-errors it leaves are `undefined symbol`s from its empty libraries, so watch
-that list for names libc itself would own (`xattr` was one).
+(P.5, phase 3) gets a dedicated escape test per helper: path opens, sockets and
+exec are denied.
diff --git a/src/c/libc.h b/src/c/libc.h
index f9b9876..8ae5092 100644
--- a/src/c/libc.h
+++ b/src/c/libc.h
@@ -37,3 +37,9 @@
#ifdef __linux__
#include <linux/netlink.h> /* printer hotplug uevents */
#endif
+
+#ifdef __FreeBSD__
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <sys/user.h> /* struct kinfo_proc: the process list */
+#endif
diff --git a/src/files/dirsize.zig b/src/files/dirsize.zig
index e92ded5..7b8a612 100644
--- a/src/files/dirsize.zig
+++ b/src/files/dirsize.zig
@@ -1,10 +1,9 @@
const std = @import("std");
-const builtin = @import("builtin");
+const platform = @import("platform");
const c = @import("c.zig").api;
-const linux = std.os.linux;
const Allocator = std.mem.Allocator;
+const dirwalk = platform.dirwalk;
-pub const STATX_ATTR_MOUNT_ROOT: u64 = 0x2000;
pub const queue_capacity: usize = 256;
pub const buffer_size: usize = 65536;
@@ -69,7 +68,7 @@ pub const QueueEntry = struct {
const WorkerContext = struct {
allocator: Allocator,
- buffers: [64]?[]align(@alignOf(linux.dirent64)) u8 = @splat(null),
+ buffers: [64]?[]align(dirwalk.buffer_align) u8 = @splat(null),
pub fn init(allocator: Allocator) WorkerContext {
return .{ .allocator = allocator };
@@ -84,19 +83,19 @@ const WorkerContext = struct {
}
}
- pub fn getBuffer(self: *WorkerContext, depth: usize) ![]align(@alignOf(linux.dirent64)) u8 {
+ pub fn getBuffer(self: *WorkerContext, depth: usize) ![]align(dirwalk.buffer_align) u8 {
if (depth < self.buffers.len) {
if (self.buffers[depth]) |slice| {
return slice;
}
- const slice = try self.allocator.alignedAlloc(u8, .fromByteUnits(@alignOf(linux.dirent64)), buffer_size);
+ const slice = try self.allocator.alignedAlloc(u8, .fromByteUnits(dirwalk.buffer_align), buffer_size);
self.buffers[depth] = slice;
return slice;
}
- return self.allocator.alignedAlloc(u8, .fromByteUnits(@alignOf(linux.dirent64)), buffer_size);
+ return self.allocator.alignedAlloc(u8, .fromByteUnits(dirwalk.buffer_align), buffer_size);
}
- pub fn releaseBuffer(self: *WorkerContext, depth: usize, buf: []align(@alignOf(linux.dirent64)) u8) void {
+ pub fn releaseBuffer(self: *WorkerContext, depth: usize, buf: []align(dirwalk.buffer_align) u8) void {
if (depth >= self.buffers.len) {
self.allocator.free(buf);
}
@@ -212,9 +211,6 @@ pub const Pool = struct {
}
pub fn startJob(self: *Pool, path: []const u8) !*Job {
- // The walk reads directories with statx and getdents64, which only Linux has; the folder
- // size column stays empty elsewhere until the scan is ported (docs/plans/freebsd.md).
- if (comptime builtin.os.tag != .linux) return error.Unsupported;
var path_buf: [4096]u8 = undefined;
const path_z = try std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0);
@@ -236,23 +232,10 @@ pub const Pool = struct {
}
errdefer _ = c.close(root_fd);
- var root_stx: linux.Statx = undefined;
- const stat_rc = linux.statx(
- root_fd,
- "",
- linux.AT.EMPTY_PATH | linux.AT.STATX_DONT_SYNC,
- linux.STATX{ .TYPE = true, .INO = true },
- &root_stx,
- );
- if (linux.errno(stat_rc) != .SUCCESS) {
- return error.StatFailed;
- }
- if ((root_stx.mode & linux.S.IFMT) != linux.S.IFDIR) {
- return error.NotDirectory;
- }
+ const root = dirwalk.statFd(root_fd) orelse return error.StatFailed;
+ if (root.kind != .directory) return error.NotDirectory;
- const dev_id = (@as(u64, root_stx.dev_major) << 32) | root_stx.dev_minor;
- const job = try Job.create(self.allocator, dev_id);
+ const job = try Job.create(self.allocator, root.dev);
errdefer job.unref();
job.pending.store(1, .release);
@@ -323,6 +306,12 @@ fn walkDirectory(pool: *Pool, ctx: *WorkerContext, job: *Job, dir_fd: c_int, dep
};
defer ctx.releaseBuffer(depth, buf);
+ var reader = dirwalk.Reader.init(dir_fd, buf) catch {
+ job.partial.store(true, .release);
+ return;
+ };
+ defer reader.deinit();
+
var local_bytes: i64 = 0;
var local_files: usize = 0;
var local_dirs: usize = 0;
@@ -338,103 +327,69 @@ fn walkDirectory(pool: *Pool, ctx: *WorkerContext, job: *Job, dir_fd: c_int, dep
while (true) {
if (job.cancelled.load(.acquire)) return;
- const rc = linux.getdents64(dir_fd, buf.ptr, @intCast(buf.len));
- const err = linux.errno(rc);
- if (err != .SUCCESS) {
- if (err != .NOENT and err != .BADF) {
- job.partial.store(true, .release);
- }
+ const name_ptr = (reader.next() catch |err| {
+ if (err == error.Failed) job.partial.store(true, .release);
return;
- }
- const nread = rc;
- if (nread == 0) return;
+ }) orelse return;
- var pos: usize = 0;
- while (pos < nread) {
- if (job.cancelled.load(.acquire)) return;
- const d: *const linux.dirent64 = @ptrCast(@alignCast(&buf[pos]));
- pos += d.reclen;
-
- const name_ptr: [*:0]const u8 = @ptrCast(&d.name);
- const name = std.mem.span(name_ptr);
- if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
-
- var stx: linux.Statx = undefined;
- const stat_rc = linux.statx(
- dir_fd,
- name_ptr,
- linux.AT.SYMLINK_NOFOLLOW | linux.AT.STATX_DONT_SYNC | linux.AT.NO_AUTOMOUNT,
- linux.STATX{ .SIZE = true, .NLINK = true, .INO = true, .TYPE = true },
- &stx,
- );
- const stat_err = linux.errno(stat_rc);
- if (stat_err != .SUCCESS) {
+ const entry = dirwalk.statAt(dir_fd, name_ptr) orelse {
+ job.partial.store(true, .release);
+ continue;
+ };
+
+ if (entry.kind == .directory) {
+ if (entry.mount_root) continue;
+ if (entry.dev != job.dev_id) continue;
+
+ const sub_fd = c.openat(dir_fd, name_ptr, c.O_RDONLY | c.O_DIRECTORY | c.O_NOFOLLOW | c.O_CLOEXEC);
+ if (sub_fd < 0) {
job.partial.store(true, .release);
continue;
}
-
- const mode_type = stx.mode & linux.S.IFMT;
- const is_dir = mode_type == linux.S.IFDIR;
-
- if (is_dir) {
- const raw_attr: u64 = @bitCast(stx.attributes);
- if ((raw_attr & STATX_ATTR_MOUNT_ROOT) != 0) continue;
-
- const dev = (@as(u64, stx.dev_major) << 32) | stx.dev_minor;
- if (dev != job.dev_id) continue;
-
- const sub_fd = c.openat(dir_fd, name_ptr, c.O_RDONLY | c.O_DIRECTORY | c.O_NOFOLLOW | c.O_CLOEXEC);
- if (sub_fd < 0) {
- job.partial.store(true, .release);
- continue;
+ local_dirs += 1;
+
+ _ = job.pending.fetchAdd(1, .monotonic);
+ job.ref();
+ if (!pool.tryPush(job, sub_fd)) {
+ walkDirectory(pool, ctx, job, sub_fd, depth + 1);
+ _ = c.close(sub_fd);
+ if (job.pending.fetchSub(1, .acq_rel) == 1) {
+ pool.notifyDone(job);
}
- local_dirs += 1;
-
- _ = job.pending.fetchAdd(1, .monotonic);
- job.ref();
- if (!pool.tryPush(job, sub_fd)) {
- walkDirectory(pool, ctx, job, sub_fd, depth + 1);
- _ = c.close(sub_fd);
- if (job.pending.fetchSub(1, .acq_rel) == 1) {
- pool.notifyDone(job);
- }
- job.unref();
- }
- } else {
- const is_reg = mode_type == linux.S.IFREG;
- if (is_reg and stx.nlink > 1) {
- const dev = (@as(u64, stx.dev_major) << 32) | stx.dev_minor;
- const key = InodeKey{ .dev = dev, .ino = stx.ino };
- _ = c.pthread_mutex_lock(&job.hardlink_mutex);
- const gop = job.seen_hardlinks.getOrPut(key) catch {
- _ = c.pthread_mutex_unlock(&job.hardlink_mutex);
- job.partial.store(true, .release);
- continue;
- };
- const already_seen = gop.found_existing;
+ job.unref();
+ }
+ } else {
+ if (entry.kind == .regular and entry.nlink > 1) {
+ const key = InodeKey{ .dev = entry.dev, .ino = entry.ino };
+ _ = c.pthread_mutex_lock(&job.hardlink_mutex);
+ const gop = job.seen_hardlinks.getOrPut(key) catch {
_ = c.pthread_mutex_unlock(&job.hardlink_mutex);
+ job.partial.store(true, .release);
+ continue;
+ };
+ const already_seen = gop.found_existing;
+ _ = c.pthread_mutex_unlock(&job.hardlink_mutex);
- if (!already_seen) {
- local_bytes += @intCast(stx.size);
- local_files += 1;
- }
- } else {
- local_bytes += @intCast(stx.size);
+ if (!already_seen) {
+ local_bytes += @intCast(entry.size);
local_files += 1;
}
+ } else {
+ local_bytes += @intCast(entry.size);
+ local_files += 1;
}
+ }
- local_count += 1;
- if (local_count >= 4096) {
- _ = job.bytes.fetchAdd(local_bytes, .monotonic);
- _ = job.files.fetchAdd(local_files, .monotonic);
- _ = job.dirs.fetchAdd(local_dirs, .monotonic);
- local_bytes = 0;
- local_files = 0;
- local_dirs = 0;
- local_count = 0;
- if (job.cancelled.load(.acquire)) return;
- }
+ local_count += 1;
+ if (local_count >= 4096) {
+ _ = job.bytes.fetchAdd(local_bytes, .monotonic);
+ _ = job.files.fetchAdd(local_files, .monotonic);
+ _ = job.dirs.fetchAdd(local_dirs, .monotonic);
+ local_bytes = 0;
+ local_files = 0;
+ local_dirs = 0;
+ local_count = 0;
+ if (job.cancelled.load(.acquire)) return;
}
}
}
diff --git a/src/files/dirsize_tests.zig b/src/files/dirsize_tests.zig
index eead664..ad56646 100644
--- a/src/files/dirsize_tests.zig
+++ b/src/files/dirsize_tests.zig
@@ -36,7 +36,6 @@ pub fn countOpenFds() !usize {
}
test "dirsize: nested folders give the right total" {
- if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -88,7 +87,6 @@ test "dirsize: nested folders give the right total" {
}
test "dirsize: a hardlink pair is counted once" {
- if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -127,7 +125,6 @@ test "dirsize: a hardlink pair is counted once" {
}
test "dirsize: a symlink loop is not followed" {
- if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -166,7 +163,6 @@ test "dirsize: a symlink loop is not followed" {
}
test "dirsize: an unreadable folder gives a partial result" {
- if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -206,7 +202,7 @@ test "dirsize: an unreadable folder gives a partial result" {
}
test "dirsize: cancelling mid-walk leaks no fds" {
- if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // counts /proc/self/fd, which FreeBSD lacks without fdescfs
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -243,7 +239,6 @@ test "dirsize: cancelling mid-walk leaks no fds" {
}
test "dirsize: a mount boundary is not crossed" {
- if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
const pool = try dirsize_mod.Pool.init(a);
defer pool.deinit();
@@ -259,7 +254,6 @@ test "dirsize: a mount boundary is not crossed" {
}
test "App folder size calculation and display lifecycle" {
- if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -374,7 +368,6 @@ test "App size sort: calculated folders sort by apparent size, uncalculated last
}
test "App clicking dash starts calculation without changing selection" {
- if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
diff --git a/src/files/ops.zig b/src/files/ops.zig
index 5dd8fdf..39bb482 100644
--- a/src/files/ops.zig
+++ b/src/files/ops.zig
@@ -115,7 +115,9 @@ pub fn deleteItems(io: std.Io, paths: []const []const u8) !void {
if (paths.len == 0) return;
var args: std.ArrayList([]const u8) = .empty;
defer args.deinit(std.heap.c_allocator);
- try args.appendSlice(std.heap.c_allocator, &.{ "rm", "-r", "--interactive=never", "--" });
+ // GNU rm takes `--interactive=never`; FreeBSD's rm only has `-f`.
+ const never_prompt = if (@import("builtin").os.tag == .linux) "--interactive=never" else "-f";
+ try args.appendSlice(std.heap.c_allocator, &.{ "rm", "-r", never_prompt, "--" });
try args.appendSlice(std.heap.c_allocator, paths);
var child = try std.process.spawn(io, .{ .argv = args.items });
const result = try child.wait(io);
diff --git a/src/input/motion.zig b/src/input/motion.zig
index 23fbf5c..b64b7dd 100644
--- a/src/input/motion.zig
+++ b/src/input/motion.zig
@@ -201,15 +201,19 @@ fn updateWidgetProximity(input: *Input) void {
}
}
+ // Mapping the window can move the camera (and so the cursor) before its
+ // first layout has built `root`.
if (input.open_control_center) |cc| {
- const local = cc.localPoint(input.cursor.x, input.cursor.y);
- if (ui_input.updateButtonProximity(&cc.root, @floatCast(local.x), @floatCast(local.y), .{
- .x = 0,
- .y = 0,
- .w = @floatFromInt(cc.panel_box.width),
- .h = @floatFromInt(cc.panel_box.height),
- })) {
- cc.requestWidgetRepaint();
+ if (cc.built_page != null) {
+ const local = cc.localPoint(input.cursor.x, input.cursor.y);
+ if (ui_input.updateButtonProximity(&cc.root, @floatCast(local.x), @floatCast(local.y), .{
+ .x = 0,
+ .y = 0,
+ .w = @floatFromInt(cc.panel_box.width),
+ .h = @floatFromInt(cc.panel_box.height),
+ })) {
+ cc.requestWidgetRepaint();
+ }
}
}
diff --git a/src/input/virtual.zig b/src/input/virtual.zig
index beda86b..04c26fc 100644
--- a/src/input/virtual.zig
+++ b/src/input/virtual.zig
@@ -323,16 +323,11 @@ pub const VirtualInput = struct {
}
pub fn nowMs() u32 {
- const timespec = extern struct {
- tv_sec: c_long,
- tv_nsec: c_long,
- };
- const clock_gettime_fn = struct {
- extern fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
- }.clock_gettime;
- var ts: timespec = undefined;
- _ = clock_gettime_fn(1, &ts); // 1 = CLOCK_MONOTONIC
- const ms: u64 = @intCast(@as(i64, ts.tv_sec) * 1000 + @divTrunc(ts.tv_nsec, 1_000_000));
+ // The OS's own constant: 1 is CLOCK_MONOTONIC on Linux but CLOCK_VIRTUAL
+ // (process CPU time) on FreeBSD.
+ var ts: std.posix.timespec = undefined;
+ if (std.posix.errno(std.posix.system.clock_gettime(std.posix.CLOCK.MONOTONIC, &ts)) != .SUCCESS) return 0;
+ const ms: u64 = @intCast(@as(i64, ts.sec) * 1000 + @divTrunc(ts.nsec, 1_000_000));
return @truncate(ms);
}
};
diff --git a/src/ipc/server.zig b/src/ipc/server.zig
index 5ca13ba..0b3ec18 100644
--- a/src/ipc/server.zig
+++ b/src/ipc/server.zig
@@ -348,25 +348,37 @@ pub fn parseFlatpakAppId(content: []const u8) ?[]const u8 {
return null;
}
-fn detectSandbox(pid: i32, client_fd: c_int, allocator: std.mem.Allocator) ?SandboxCaller {
- if (pid <= 0) return null;
+/// Has the process that made the connection exited (a zombie counts), or is it
+/// unknown? Without a pidfd from the socket this asks about the credentials'
+/// pid, which a reuse could have handed to another process.
+fn peerGone(process: ?platform.child.Handle, pid: i32) bool {
+ return if (process) |handle| handle.exited() else !platform.child.exists(pid);
+}
+
+/// Null means "not sandboxed". `error.Unclassifiable` is a connector that is
+/// gone or that this process cannot see: its credentials outlive it, and a
+/// child that inherited the socket (and the sandbox) may still be writing, so
+/// nothing can be said and the connection is refused.
+fn detectSandbox(pid: i32, client_fd: c_int, allocator: std.mem.Allocator) error{Unclassifiable}!?SandboxCaller {
+ // SO_PEERCRED gives pid 0 for a process in a pid namespace we cannot see.
+ if (pid <= 0) return error.Unclassifiable;
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();
+ if (peerGone(process, pid)) return error.Unclassifiable;
var proc_buf: [64]u8 = undefined;
const proc_path = std.fmt.bufPrintSentinel(&proc_buf, "/proc/{d}", .{pid}, 0) catch return null;
const proc_fd = c.open(proc_path.ptr, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true });
- if (proc_fd < 0) return null;
+ // Alive but without a /proc entry: no procfs here, so there is nothing to read.
+ if (proc_fd < 0) return if (peerGone(process, pid)) error.Unclassifiable else null;
defer closeFd(proc_fd);
const file_fd = c.openat(proc_fd, "root/.flatpak-info", .{ .ACCMODE = .RDONLY, .CLOEXEC = true });
if (file_fd < 0) {
const err = std.posix.errno(file_fd);
- if (err == .NOENT) {
- return null;
- }
+ if (err == .NOENT) return if (peerGone(process, pid)) error.Unclassifiable else null;
return .{ .app_id = null, .engine = "org.flatpak" };
}
defer closeFd(file_fd);
@@ -414,7 +426,11 @@ fn handleListenerFd(fd: c_int, mask: wl.EventMask, ipc: *IpcServer) c_int {
return 0;
}
- const sandbox_opt = detectSandbox(peer.pid, client_fd, ipc.allocator);
+ const sandbox_opt = detectSandbox(peer.pid, client_fd, ipc.allocator) catch {
+ log.warn("rejecting IPC connection: its process exited or cannot be seen, so it cannot be checked for a sandbox", .{});
+ closeFd(client_fd);
+ return 0;
+ };
if (sandbox_opt) |sb| {
const groups = ipc.compositor.config.sandboxAllowGroups(sb.app_id, sb.engine);
if (!groups.contains(.ipc)) {
diff --git a/src/msg/main.zig b/src/msg/main.zig
index 59587dd..d8f9969 100644
--- a/src/msg/main.zig
+++ b/src/msg/main.zig
@@ -31,6 +31,14 @@ pub fn closeFd(fd: std.posix.fd_t) void {
_ = std.c.close(fd);
}
+extern "c" fn strerror(errnum: c_int) [*:0]const u8;
+
+/// The libc text for why the libc call that returned `rc` failed ("Operation not
+/// permitted"). Call it before anything else that could touch errno.
+pub fn errnoText(rc: anytype) []const u8 {
+ return std.mem.span(strerror(@intFromEnum(std.posix.errno(rc))));
+}
+
pub fn getEnv(key: [*:0]const u8) ?[]const u8 {
if (std.c.getenv(key)) |ptr| {
return std.mem.span(ptr);
@@ -144,8 +152,9 @@ pub fn runMsg(init: std.process.Init, allocator: std.mem.Allocator) !void {
@memcpy(addr.path[0..socket_path.len], socket_path);
const addr_len = @as(std.posix.socklen_t, @intCast(@offsetOf(std.posix.sockaddr.un, "path") + socket_path.len + 1));
- if (c.connect(sock_fd, @ptrCast(&addr), addr_len) < 0) {
- std.debug.print("error: failed to connect to socket {s}\n", .{socket_path});
+ const connect_rc = c.connect(sock_fd, @ptrCast(&addr), addr_len);
+ if (connect_rc < 0) {
+ std.debug.print("error: failed to connect to socket {s}: {s}\n", .{ socket_path, errnoText(connect_rc) });
std.process.exit(1);
}
diff --git a/src/msg/msg_doctor.zig b/src/msg/msg_doctor.zig
index 0000521..3c40c07 100644
--- a/src/msg/msg_doctor.zig
+++ b/src/msg/msg_doctor.zig
@@ -3,6 +3,7 @@
const std = @import("std");
const protocol = @import("protocol");
const closeFd = @import("main.zig").closeFd;
+const errnoText = @import("main.zig").errnoText;
pub fn sendDoctorQuery(sock_fd: std.posix.fd_t, query: []const u8, allocator: std.mem.Allocator) ?std.json.Parsed(std.json.Value) {
const c = std.posix.system;
@@ -65,16 +66,24 @@ pub fn runDoctor(socket_path: []const u8, allocator: std.mem.Allocator, is_json:
_ = c.setsockopt(sock_fd, std.posix.SOL.SOCKET, std.posix.SO.RCVTIMEO, @ptrCast(&tv), @sizeOf(std.posix.timeval));
_ = c.setsockopt(sock_fd, std.posix.SOL.SOCKET, std.posix.SO.SNDTIMEO, @ptrCast(&tv), @sizeOf(std.posix.timeval));
- if (c.connect(sock_fd, @ptrCast(&addr), addr_len) < 0) {
+ const connect_rc = c.connect(sock_fd, @ptrCast(&addr), addr_len);
+ if (connect_rc < 0) {
+ // The errno tells these apart: a missing or refused socket means no compositor,
+ // EPERM/EACCES means something (a sandbox, file modes) forbids the connection.
+ const reason = errnoText(connect_rc);
+ const hint = switch (std.posix.errno(connect_rc)) {
+ .NOENT, .CONNREFUSED => ", compositor not running or socket path invalid",
+ else => "",
+ };
if (is_json) {
- std.debug.print("{{\"status\":\"error\",\"error\":\"connection refused\",\"socket\":{f}}}\n", .{std.json.fmt(socket_path, .{})});
+ std.debug.print("{{\"status\":\"error\",\"error\":\"connection failed\",\"reason\":{f},\"socket\":{f}}}\n", .{ std.json.fmt(reason, .{}), std.json.fmt(socket_path, .{}) });
} else {
std.debug.print(
- \\\rediwm doctor
- \\\=============
- \\\[✗] Socket: {s} (connection failed: compositor not running or socket path invalid)
- \\\
- , .{socket_path});
+ \\rediwm doctor
+ \\=============
+ \\[✗] Socket: {s} (connection failed: {s}{s})
+ \\
+ , .{ socket_path, reason, hint });
}
std.process.exit(1);
}
diff --git a/src/platform/AGENTS.md b/src/platform/AGENTS.md
index 785ce8f..85032fb 100644
--- a/src/platform/AGENTS.md
+++ b/src/platform/AGENTS.md
@@ -7,7 +7,8 @@ privileges (`process.zig`), descriptors that wake a poll loop (`wake.zig`),
where the system's helper programs live (`tool.zig`), seccomp-BPF filters
(`seccomp.zig`, for the PDF viewer and the theme helper), and
`child.h`/`self_exe.h`/`peer.h`/`process.h` for C and C++, and `fs.zig`
-(rename without replacing, stat). Std only, no compositor imports. Linux and
+(rename without replacing, stat), and `dirwalk.zig` (reading a directory and
+examining its entries, for the Files folder-size walk). Std only, no compositor imports. Linux and
FreeBSD: a part is one file with a `switch (builtin.os.tag)` per function
(`peer`, `process`, `wake`, `watch`, `exe`, `fs`), or a facade over
`child_linux.zig` and `child_freebsd.zig`. A part not ported to another OS
@@ -57,13 +58,16 @@ any target). FreeBSD notes are in `docs/plans/freebsd.md`.
an unreaped zombie there, true on Linux.
* **`fs.renameNoReplace` is atomic only on Linux.** FreeBSD hard-links and
unlinks (a failure leaves both names) and checks-then-renames a directory.
+* **`dirwalk.Reader` names are valid until the next call.** The Linux reader
+ fills the caller's buffer (the walk keeps one per depth); FreeBSD's ignores
+ it and opens its own `DIR` on a copy of the descriptor. `mount_root` is a
+ Linux answer; FreeBSD's walk stops at a different device only.
* 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): the supervisor's and the
DM's event loops and process calls (`signalfd`, `epoll`, `poll`, `fork`,
-`kill`, `wait4`; neither program is built on FreeBSD), `statx` and `getdents64`
-in the Files folder-size walk (it refuses on other systems), `/proc` walks, the
+`kill`, `wait4`; neither program is built on FreeBSD), `/proc` walks, the
terminal's per-message `SCM_CREDENTIALS` check (`files/terminal/engine.c`, which
refuses to start a terminal on other systems), the DRM driver ioctl in
`Output.zig` and the two seccomp policy tables. Everything else outside this
diff --git a/src/platform/dirwalk.zig b/src/platform/dirwalk.zig
new file mode 100644
index 0000000..6247016
--- /dev/null
+++ b/src/platform/dirwalk.zig
@@ -0,0 +1,173 @@
+//! Reading a directory and examining its entries, for the Files folder-size
+//! walk. Linux reads with `getdents64` into a buffer the caller reuses and
+//! examines with `statx`; FreeBSD reads with `fdopendir`/`readdir` and
+//! examines with `fstatat`. An entry is never followed if it is a link.
+const std = @import("std");
+const builtin = @import("builtin");
+const linux = std.os.linux;
+
+comptime {
+ if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
+ @compileError("platform.dirwalk is not ported to this OS yet (docs/plans/freebsd.md, phase 1)");
+}
+
+pub const Kind = enum { directory, regular, other };
+
+pub const Entry = struct {
+ size: u64,
+ nlink: u64,
+ ino: u64,
+ /// Equal for entries on the same file system.
+ dev: u64,
+ kind: Kind,
+ /// The root of a mounted file system. Linux says so even for a second
+ /// mount of the same device; FreeBSD has only the device to compare.
+ mount_root: bool,
+};
+
+/// Alignment of the buffer given to `Reader.init`.
+pub const buffer_align = @alignOf(u64);
+
+pub const ReadError = error{
+ /// The directory was removed or its descriptor closed while it was read.
+ Gone,
+ Failed,
+};
+
+/// The entries of one open directory, without "." and "..". A name is valid
+/// until the next call.
+pub const Reader = if (builtin.os.tag == .linux) LinuxReader else FreebsdReader;
+
+const LinuxReader = struct {
+ fd: c_int,
+ buf: []align(buffer_align) u8,
+ pos: usize = 0,
+ len: usize = 0,
+
+ /// Reads into `buf` (a few KiB at least); `fd` stays the caller's.
+ pub fn init(fd: c_int, buf: []align(buffer_align) u8) ReadError!LinuxReader {
+ return .{ .fd = fd, .buf = buf };
+ }
+
+ pub fn deinit(_: *LinuxReader) void {}
+
+ pub fn next(self: *LinuxReader) ReadError!?[*:0]const u8 {
+ while (true) {
+ if (self.pos >= self.len) {
+ const rc = linux.getdents64(self.fd, self.buf.ptr, @intCast(self.buf.len));
+ switch (linux.errno(rc)) {
+ .SUCCESS => {},
+ .NOENT, .BADF => return error.Gone,
+ else => return error.Failed,
+ }
+ if (rc == 0) return null;
+ self.pos = 0;
+ self.len = rc;
+ }
+ const d: *const linux.dirent64 = @ptrCast(@alignCast(&self.buf[self.pos]));
+ self.pos += d.reclen;
+ const name: [*:0]const u8 = @ptrCast(&d.name);
+ if (!isDot(name)) return name;
+ }
+ }
+};
+
+const FreebsdReader = struct {
+ dir: *std.c.DIR,
+
+ /// `buf` is not used. `fdopendir` owns the descriptor it is given, so it
+ /// gets a copy and `fd` stays the caller's.
+ pub fn init(fd: c_int, _: []align(buffer_align) u8) ReadError!FreebsdReader {
+ const copy = std.c.fcntl(fd, std.c.F.DUPFD_CLOEXEC, @as(c_int, 0));
+ if (copy < 0) return error.Failed;
+ const dir = std.c.fdopendir(copy) orelse {
+ _ = std.c.close(copy);
+ return error.Failed;
+ };
+ return .{ .dir = dir };
+ }
+
+ pub fn deinit(self: *FreebsdReader) void {
+ _ = std.c.closedir(self.dir);
+ }
+
+ pub fn next(self: *FreebsdReader) ReadError!?[*:0]const u8 {
+ while (true) {
+ // readdir returns null at the end and on an error; only errno tells.
+ std.c._errno().* = 0;
+ const entry = std.c.readdir(self.dir) orelse {
+ const err = std.c._errno().*;
+ if (err == 0) return null;
+ if (err == @backingInt(std.c.E.NOENT) or err == @backingInt(std.c.E.BADF)) return error.Gone;
+ return error.Failed;
+ };
+ const name: [*:0]const u8 = @ptrCast(&entry.name);
+ if (!isDot(name)) return name;
+ }
+ }
+};
+
+fn isDot(name: [*:0]const u8) bool {
+ const text = std.mem.span(name);
+ return std.mem.eql(u8, text, ".") or std.mem.eql(u8, text, "..");
+}
+
+/// `name` in the directory `dir_fd`, or null if it cannot be examined.
+pub fn statAt(dir_fd: c_int, name: [*:0]const u8) ?Entry {
+ return switch (builtin.os.tag) {
+ .linux => linuxStat(dir_fd, name, linux.AT.SYMLINK_NOFOLLOW | linux.AT.NO_AUTOMOUNT),
+ .freebsd => freebsdStat(dir_fd, name),
+ else => unreachable,
+ };
+}
+
+/// What an open descriptor names.
+pub fn statFd(fd: c_int) ?Entry {
+ return switch (builtin.os.tag) {
+ .linux => linuxStat(fd, "", linux.AT.EMPTY_PATH),
+ .freebsd => freebsdStatFd(fd),
+ else => unreachable,
+ };
+}
+
+/// `STATX_ATTR_MOUNT_ROOT`, which the build's headers may not name.
+const statx_attr_mount_root: u64 = 0x2000;
+
+fn linuxStat(dir_fd: c_int, name: [*:0]const u8, flags: u32) ?Entry {
+ var stx: linux.Statx = undefined;
+ const rc = linux.statx(dir_fd, name, flags | linux.AT.STATX_DONT_SYNC, linux.STATX{ .SIZE = true, .NLINK = true, .INO = true, .TYPE = true }, &stx);
+ if (linux.errno(rc) != .SUCCESS) return null;
+ const type_bits = stx.mode & linux.S.IFMT;
+ return .{
+ .size = stx.size,
+ .nlink = stx.nlink,
+ .ino = stx.ino,
+ .dev = (@as(u64, stx.dev_major) << 32) | stx.dev_minor,
+ .kind = if (type_bits == linux.S.IFDIR) .directory else if (type_bits == linux.S.IFREG) .regular else .other,
+ .mount_root = @as(u64, @bitCast(stx.attributes)) & statx_attr_mount_root != 0,
+ };
+}
+
+fn freebsdStat(dir_fd: c_int, name: [*:0]const u8) ?Entry {
+ var info: std.c.Stat = undefined;
+ if (std.c.fstatat(dir_fd, name, &info, std.c.AT.SYMLINK_NOFOLLOW) != 0) return null;
+ return freebsdEntry(&info);
+}
+
+fn freebsdStatFd(fd: c_int) ?Entry {
+ var info: std.c.Stat = undefined;
+ if (std.c.fstat(fd, &info) != 0) return null;
+ return freebsdEntry(&info);
+}
+
+fn freebsdEntry(info: *const std.c.Stat) Entry {
+ const type_bits = info.mode & std.posix.S.IFMT;
+ return .{
+ .size = @intCast(@max(info.size, 0)),
+ .nlink = @intCast(info.nlink),
+ .ino = @intCast(info.ino),
+ .dev = @intCast(info.dev),
+ .kind = if (type_bits == std.posix.S.IFDIR) .directory else if (type_bits == std.posix.S.IFREG) .regular else .other,
+ .mount_root = false,
+ };
+}
diff --git a/src/platform/mod.zig b/src/platform/mod.zig
index 52fe7f5..fa2c667 100644
--- a/src/platform/mod.zig
+++ b/src/platform/mod.zig
@@ -1,12 +1,13 @@
//! Everything that differs between operating systems, behind one interface:
//! child processes, file-change notification, the program's own path, where
//! the system's helper programs live, who is on the other end of a unix socket,
-//! renaming without replacing,
+//! renaming without replacing, reading and examining directories,
//! process attributes (no core dumps, no new privileges), wake descriptors and
//! syscall filters.
//! 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 dirwalk = @import("dirwalk.zig");
pub const exe = @import("exe.zig");
pub const fs = @import("fs.zig");
pub const peer = @import("peer.zig");
@@ -21,6 +22,7 @@ pub const tool = @import("tool.zig");
test {
_ = child;
+ _ = dirwalk;
_ = exe;
_ = fs;
_ = peer;
diff --git a/src/platform/peer.zig b/src/platform/peer.zig
index 502db1d..84e6869 100644
--- a/src/platform/peer.zig
+++ b/src/platform/peer.zig
@@ -12,7 +12,7 @@ const linux = std.os.linux;
// another OS must fail here and not ask its kernel something else.
comptime {
if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
- @compileError("platform.peer is not ported to this OS yet (docs/plans/freebsd.md, P.9)");
+ @compileError("platform.peer is not ported to this OS yet (docs/plans/freebsd.md)");
}
pub const Credentials = struct {
diff --git a/src/platform/process.zig b/src/platform/process.zig
index 94bbc2d..ccd89eb 100644
--- a/src/platform/process.zig
+++ b/src/platform/process.zig
@@ -10,7 +10,7 @@ const child = @import("child.zig");
// another OS must fail here and not ask its kernel something else.
comptime {
if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
- @compileError("platform.process is not ported to this OS yet (docs/plans/freebsd.md, P.4)");
+ @compileError("platform.process is not ported to this OS yet (docs/plans/freebsd.md)");
}
/// FreeBSD's procctl(2): the commands and values of `sys/procctl.h`.
diff --git a/src/platform/wake.zig b/src/platform/wake.zig
index 7a6a80b..88d53ec 100644
--- a/src/platform/wake.zig
+++ b/src/platform/wake.zig
@@ -9,7 +9,7 @@ const linux = std.os.linux;
// another OS must fail here and not ask its kernel something else.
comptime {
if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
- @compileError("platform.wake is not ported to this OS yet (docs/plans/freebsd.md, P.4)");
+ @compileError("platform.wake is not ported to this OS yet (docs/plans/freebsd.md)");
}
/// A new wake descriptor: close-on-exec, non-blocking, count zero. The caller
diff --git a/src/system_monitor/AGENTS.md b/src/system_monitor/AGENTS.md
index d568f97..cc22ae4 100644
--- a/src/system_monitor/AGENTS.md
+++ b/src/system_monitor/AGENTS.md
@@ -6,7 +6,8 @@
* **`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
+ (`kern.proc` sysctls; a `Process` holds the `kinfo_proc` taken at open, CPU is
+ in microseconds). 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`.
diff --git a/src/system_monitor/proc.zig b/src/system_monitor/proc.zig
index 3828a52..6b488d6 100644
--- a/src/system_monitor/proc.zig
+++ b/src/system_monitor/proc.zig
@@ -1,8 +1,8 @@
//! 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:
+//! (`proc_linux.zig` reads `/proc`, `proc_freebsd.zig` the `kern.proc` sysctls). A
+//! backend provides:
//!
//! * `Process`: `open(pid)`, `close`, `stat(buf)`, `uids(buf)`, `exePath(buf)`.
//! One open `Process` describes one task, so its three reads agree.
diff --git a/src/system_monitor/proc_freebsd.zig b/src/system_monitor/proc_freebsd.zig
index 3d01c60..e3bdc8b 100644
--- a/src/system_monitor/proc_freebsd.zig
+++ b/src/system_monitor/proc_freebsd.zig
@@ -1,44 +1,182 @@
-//! 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.
+//! FreeBSD backend of the process list: `kern.proc` sysctls, since FreeBSD has
+//! no procfs by default. One `Process` holds the `kinfo_proc` taken when it was
+//! opened, so its three reads agree. CPU is in microseconds (`ki_runtime`, so
+//! `ticksPerSecond` is 1e6) and RSS in pages. `start` is the start time in
+//! microseconds, which with the pid names one process.
+//!
+//! Not read: swap (needs `vm.swap_info`), and a long command name (`ki_comm`
+//! holds 19 characters).
+const std = @import("std");
const common = @import("proc_common.zig");
+const c = common.c;
const Error = common.Error;
+const Info = c.struct_kinfo_proc;
+
+const ctl_kern = 1;
+const kern_proc = 14;
+const kern_proc_all = 0;
+const kern_proc_pid = 1;
+const kern_proc_pathname = 12;
+
+const allocator = std.heap.c_allocator;
+
+fn classify(err: std.posix.E) Error {
+ return switch (err) {
+ .PERM, .ACCES => error.PermissionDenied,
+ .SRCH => error.ProcessExited,
+ .NOMEM => error.DataTooLarge,
+ else => error.ReadFailed,
+ };
+}
+
+fn lastError() Error {
+ return classify(std.posix.errno(@as(c_int, -1)));
+}
+
pub const Process = struct {
- pub fn open(_: i32) Error!Process {
- return error.Unsupported;
+ info: Info,
+ pid: i32,
+
+ pub fn open(pid: i32) Error!Process {
+ var mib = [_]c_int{ ctl_kern, kern_proc, kern_proc_pid, pid };
+ var self: Process = .{ .info = undefined, .pid = pid };
+ var len: usize = @sizeOf(Info);
+ if (std.c.sysctl(&mib, mib.len, &self.info, &len, null, 0) != 0) return lastError();
+ // An unknown pid is a success with nothing returned.
+ if (len == 0) return error.ProcessExited;
+ if (len != @sizeOf(Info) or self.info.ki_structsize != @sizeOf(Info)) return error.ReadFailed;
+ if (self.info.ki_pid != pid) return error.ProcessExited;
+ return self;
}
+
pub fn close(_: Process) void {}
- pub fn stat(_: Process, _: []u8) Error!common.Stat {
- return error.Unsupported;
+
+ pub fn stat(self: Process, buf: []u8) Error!common.Stat {
+ const comm: *const [@sizeOf(@TypeOf(self.info.ki_comm))]u8 = @ptrCast(&self.info.ki_comm);
+ const name = std.mem.sliceTo(comm, 0);
+ if (name.len > buf.len) return error.DataTooLarge;
+ @memcpy(buf[0..name.len], name);
+ const start = self.info.ki_start;
+ return .{
+ .name = buf[0..name.len],
+ .state = stateLetter(@bitCast(self.info.ki_stat)),
+ .cpu = self.info.ki_runtime,
+ .start = @as(u64, @intCast(@max(start.tv_sec, 0))) * 1_000_000 + @as(u64, @intCast(@max(start.tv_usec, 0))),
+ .rss = @intCast(@max(self.info.ki_rssize, 0)),
+ .ppid = self.info.ki_ppid,
+ };
}
- pub fn uids(_: Process, _: []u8) Error!common.Uids {
- return error.Unsupported;
+
+ /// Real, effective, saved and (FreeBSD has no such thing) file system uid.
+ pub fn uids(self: Process, _: []u8) Error!common.Uids {
+ return .{ self.info.ki_ruid, self.info.ki_uid, self.info.ki_svuid, self.info.ki_uid };
}
- pub fn exePath(_: Process, _: []u8) Error![]const u8 {
- return error.Unsupported;
+
+ /// Read by pid when asked, so a number reused since `open` would answer for
+ /// the new process; callers also compare `start` (see `actions.zig`).
+ pub fn exePath(self: Process, buf: []u8) Error![]const u8 {
+ var mib = [_]c_int{ ctl_kern, kern_proc, kern_proc_pathname, self.pid };
+ var len: usize = buf.len;
+ if (std.c.sysctl(&mib, mib.len, buf.ptr, &len, null, 0) != 0) return lastError();
+ const path = std.mem.sliceTo(buf[0..len], 0);
+ // Kernel threads have none.
+ if (path.len == 0) return error.IdentityUnavailable;
+ return path;
}
};
+/// The letters Linux's `/proc/<pid>/stat` uses, from `ki_stat` (`sys/proc.h`).
+fn stateLetter(code: u8) u8 {
+ return switch (code) {
+ 1 => 'I', // SIDL: being created
+ 2 => 'R', // SRUN
+ 3 => 'S', // SSLEEP
+ 4 => 'T', // SSTOP
+ 5 => 'Z', // SZOMB
+ 6, 7 => 'D', // SWAIT, SLOCK
+ else => '?',
+ };
+}
+
pub const List = struct {
+ entries: []Info,
+ count: usize,
+ index: usize = 0,
+
pub fn open() ?List {
+ var mib = [_]c_int{ ctl_kern, kern_proc, kern_proc_all };
+ var size: usize = 0;
+ if (std.c.sysctl(&mib, mib.len, null, &size, null, 0) != 0) return null;
+ // The table can grow between the size query and the read: leave room
+ // and retry when the kernel still says it is too small.
+ var attempt: usize = 0;
+ while (attempt < 4) : (attempt += 1) {
+ const capacity = size / @sizeOf(Info) + 32 + size / @sizeOf(Info) / 8;
+ const entries = allocator.alloc(Info, capacity) catch return null;
+ var len: usize = capacity * @sizeOf(Info);
+ if (std.c.sysctl(&mib, mib.len, entries.ptr, &len, null, 0) == 0) {
+ const count = len / @sizeOf(Info);
+ if (len % @sizeOf(Info) == 0 and (count == 0 or entries[0].ki_structsize == @sizeOf(Info)))
+ return .{ .entries = entries, .count = count };
+ allocator.free(entries);
+ return null;
+ }
+ allocator.free(entries);
+ if (std.posix.errno(@as(c_int, -1)) != .NOMEM) return null;
+ size = capacity * @sizeOf(Info) * 2;
+ }
return null;
}
- pub fn next(_: *List) ?i32 {
+
+ pub fn next(self: *List) ?i32 {
+ while (self.index < self.count) {
+ const pid = self.entries[self.index].ki_pid;
+ self.index += 1;
+ if (pid > 0) return pid;
+ }
return null;
}
- pub fn close(_: *List) void {}
+
+ pub fn close(self: *List) void {
+ allocator.free(self.entries);
+ self.entries = &.{};
+ self.count = 0;
+ }
};
+fn sysctlValue(comptime T: type, name: [*:0]const u8) ?T {
+ var value: T = undefined;
+ var len: usize = @sizeOf(T);
+ if (std.c.sysctlbyname(name, &value, &len, null, 0) != 0 or len != @sizeOf(T)) return null;
+ return value;
+}
+
+/// `kern.cp_time`: user, nice, system, interrupt and idle ticks, all CPUs.
pub fn cpuTotals(_: []u8) ?common.Cpu {
- return null;
+ var times: [5]c_long = undefined;
+ var len: usize = @sizeOf(@TypeOf(times));
+ if (std.c.sysctlbyname("kern.cp_time", &times, &len, null, 0) != 0 or len != @sizeOf(@TypeOf(times))) return null;
+ var total: u64 = 0;
+ for (times) |ticks| total += @intCast(@max(ticks, 0));
+ return .{ .total = total, .idle = @intCast(@max(times[4], 0)) };
}
+/// Available is free plus inactive pages. Swap is not read.
pub fn memoryTotals(_: []u8) ?common.Memory {
- return null;
+ const page = common.pageSize();
+ if (page == 0) return null;
+ const total = sysctlValue(c_ulong, "hw.physmem") orelse return null;
+ const free = sysctlValue(c_uint, "vm.stats.vm.v_free_count") orelse return null;
+ const inactive = sysctlValue(c_uint, "vm.stats.vm.v_inactive_count") orelse return null;
+ return .{
+ .total = total,
+ .available = @min(total, (@as(u64, free) + inactive) * page),
+ .swap_total = null,
+ .swap_free = null,
+ };
}
pub fn ticksPerSecond() u64 {
- return 0;
+ return 1_000_000;
}
diff --git a/src/system_monitor_tests.zig b/src/system_monitor_tests.zig
index 8afd923..c3750bc 100644
--- a/src/system_monitor_tests.zig
+++ b/src/system_monitor_tests.zig
@@ -1,5 +1,4 @@
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");
@@ -7,10 +6,33 @@ const model = @import("system_monitor/model.zig");
const collector = @import("system_monitor/collector.zig");
const actions = @import("system_monitor/actions.zig");
-/// These read /proc, which FreeBSD does not mount by default; the collector
-/// port is plan P.6.
-fn needsProcfs() !void {
- if (builtin.os.tag != .linux) return error.SkipZigTest;
+test "monitor backend lists and describes this process and the machine" {
+ const pid = proc.c.getpid();
+ var list = proc.List.open().?;
+ defer list.close();
+ var listed = false;
+ while (list.next()) |other| {
+ if (other == pid) listed = true;
+ }
+ try std.testing.expect(listed);
+
+ const process = try proc.Process.open(pid);
+ defer process.close();
+ var buf: [65536]u8 = undefined;
+ const stat = try process.stat(&buf);
+ try std.testing.expect(stat.name.len > 0);
+ try std.testing.expect(stat.state == 'R' or stat.state == 'S');
+ try std.testing.expectEqual(proc.c.getppid(), stat.ppid);
+ try std.testing.expect(stat.start != 0 and stat.rss > 0);
+ try std.testing.expect(proc.owned(try process.uids(&buf), proc.c.getuid()));
+ try std.testing.expect(std.fs.path.isAbsolute(try process.exePath(&buf)));
+ try std.testing.expectError(error.ProcessExited, proc.Process.open(std.math.maxInt(i32)));
+
+ const cpu = proc.cpuTotals(&buf).?;
+ try std.testing.expect(cpu.total > 0 and cpu.idle <= cpu.total);
+ const memory = proc.memoryTotals(&buf).?;
+ try std.testing.expect(memory.total > 0 and memory.available <= memory.total);
+ try std.testing.expect(proc.ticksPerSecond() > 0 and proc.pageSize() > 0);
}
test "monitor stat parsing preserves tricky names and rejects partial data" {
@@ -92,7 +114,6 @@ test "monitor history holds only the last 60 seconds including pause gaps" {
try std.testing.expectEqual(@as(usize, 1), history.count);
}
test "monitor action authority rejects changed identities and protects session executables" {
- try needsProcfs();
try std.testing.expect(proc.protectedName("/usr/bin/rediwm-session"));
try std.testing.expect(proc.protectedName("/usr/bin/rediwm (deleted)"));
try std.testing.expect(!proc.protectedName("/usr/bin/rediwm-files"));
@@ -103,7 +124,6 @@ test "monitor action authority rejects changed identities and protects session e
try std.testing.expectError(error.ProtectedProcess, actions.execute(.{ .pid = proc.c.getpid(), .start = own.start }, .force));
}
test "monitor real collection includes its background worker owner and cancels" {
- try needsProcfs();
var generation = std.atomic.Value(u64).init(0);
const snap = try collector.sample(&generation, 0);
defer snap.deinit();
@@ -117,7 +137,6 @@ test "monitor real collection includes its background worker owner and cancels"
}
test "monitor pidfd actions terminate only disposable fixtures and force a TERM-ignoring fixture" {
- try needsProcfs();
const io = std.testing.io;
var child = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
defer child.kill(io);
diff --git a/tests/dbus.py b/tests/dbus.py
index 414edb0..e029ab2 100644
--- a/tests/dbus.py
+++ b/tests/dbus.py
@@ -4,6 +4,7 @@ import concurrent.futures
import json
import os
import select
+import shutil
import subprocess
import sys
import time
@@ -40,8 +41,11 @@ def receive_message(peer):
def fake_peers(binary):
"""Adversarial local endpoints: authentication and framing, no bus involved."""
- for scenario in ('reject', 'auth_timeout', 'auth_overlong', 'oversized',
- 'truncated', 'bad_padding', 'fragmented_big_endian', 'abstract'):
+ scenarios = ['reject', 'auth_timeout', 'auth_overlong', 'oversized',
+ 'truncated', 'bad_padding', 'fragmented_big_endian']
+ if sys.platform.startswith('linux'):
+ scenarios.append('abstract') # only Linux has abstract unix sockets
+ for scenario in scenarios:
with tempfile.TemporaryDirectory(prefix='rediwm-dbus-') as directory:
endpoint = directory + '/bus'
address = 'unix:path=' + endpoint
@@ -157,6 +161,9 @@ def main():
__file__, sys.argv[1], '--private']))
fake_peers(sys.argv[1])
activation_env(sys.argv[1])
+ if shutil.which('busctl') is None:
+ print("D-Bus: SKIP the busctl-driven client tests (busctl is systemd's tool)")
+ return
# Exercise openSystem without ever opening the host system bus.
service = subprocess.Popen([sys.argv[1], '--system'],
env=dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=os.environ['DBUS_SESSION_BUS_ADDRESS']),
diff --git a/tests/files_associations.py b/tests/files_associations.py
index 2c05a22..1d4157d 100644
--- a/tests/files_associations.py
+++ b/tests/files_associations.py
@@ -26,7 +26,7 @@ def appimage_fixture(tmp):
'Exec="AppRun" --fixture %U\nIcon=portable\nTerminal=false\n'
'Categories=Development;\nMimeType=x-scheme-handler/rediwm-appimage-test;x-scheme-handler/rediwm-existing-test;application/x-rediwm-specific;\n'
'TryExec=/nonexistent/appimage\nPath=/nonexistent/appdir\nDBusActivatable=true\n'
- 'Actions=unsafe;\n[Desktop Action unsafe]\nName=Unsafe\nExec=/bin/false\n')
+ 'Actions=unsafe;\n[Desktop Action unsafe]\nName=Unsafe\nExec=/usr/bin/false\n')
icon = appdir / 'usr/share/icons/portable.png'
icon.parent.mkdir(parents=True)
Image.new('RGBA', (32, 32), (36, 120, 220, 255)).save(icon)
@@ -162,7 +162,7 @@ def run():
(apps / f"extra-{i}.desktop").write_text('[Desktop Entry]\nType=Application\n'
f'Name=Z Extra {i:02d}\nExec={launcher} extra-{i} %f\nTerminal=false\n')
(apps / 'existing-link.desktop').write_text('[Desktop Entry]\nType=Application\n'
- 'Name=Existing link handler\nExec=/bin/true %U\nMimeType=x-scheme-handler/rediwm-existing-test;\n')
+ 'Name=Existing link handler\nExec=/usr/bin/true %U\nMimeType=x-scheme-handler/rediwm-existing-test;\n')
defaults = ["openscad", "openscad", "override", "missing", "", "celluloid"]
(config / "mimeapps.list").write_text('[Default Applications]\n' + ''.join(
f'{t[0]}={app}.desktop;\n' for t, app in zip(types, defaults) if app) +
@@ -171,7 +171,7 @@ def run():
(home / name).write_text('cube([1, 2, 3]);\n')
env = dict(os.environ, HOME=str(home), XDG_DATA_HOME=str(data), XDG_DATA_DIRS=str(data),
XDG_CONFIG_HOME=str(config), XDG_CONFIG_DIRS=str(config), XDG_STATE_HOME=str(tmp / "state"),
- XDG_CURRENT_DESKTOP="RediWM", BROWSER="/bin/false", REDIWM_ICON_THEME="hicolor",
+ XDG_CURRENT_DESKTOP="RediWM", BROWSER="/usr/bin/false", REDIWM_ICON_THEME="hicolor",
XDG_RUNTIME_DIR=str(tmp), REDIWM_CONFIG=str(tmp / "rediwm-config.toml"),
WLR_BACKENDS="headless", REDIWM_FILES_DEVICES="0", WLR_RENDERER="gles2", WLR_HEADLESS_OUTPUTS="1", REDIWM_SCALE="1",
DBUS_SYSTEM_BUS_ADDRESS="unix:path=/nonexistent-rediwm-test-system-bus",
diff --git a/tests/i18n.py b/tests/i18n.py
index 30d524a..0423b69 100755
--- a/tests/i18n.py
+++ b/tests/i18n.py
@@ -52,7 +52,7 @@ def run():
(applications / "rediwm-i18n-fixture.desktop").write_text(
"[Desktop Entry]\nType=Application\nName=Language fixture\n"
"Name[de]=Prüfprogramm\nName[pt_BR]=Aplicativo de teste\n"
- "Exec=/bin/true\nIcon=application-x-executable\n", encoding="utf-8")
+ "Exec=/usr/bin/true\nIcon=application-x-executable\n", encoding="utf-8")
def config(language):
return ('[compositor]\nxwayland = false\n[animations]\nenabled = false\n'
diff --git a/tests/placeholder_client.c b/tests/placeholder_client.c
index 9f26e4a..5ed2d94 100644
--- a/tests/placeholder_client.c
+++ b/tests/placeholder_client.c
@@ -149,13 +149,15 @@ int main(int argc, char *argv[]) {
}
}
- if (const char *env_sleep = getenv("CLIENT_SLEEP_MS")) {
+ const char *env_sleep = getenv("CLIENT_SLEEP_MS");
+ if (env_sleep) {
sleep_ms = atoi(env_sleep);
}
if (getenv("CLIENT_EXIT_BEFORE_MAP")) {
exit_before_map = 1;
}
- if (const char *env_app = getenv("CLIENT_APP_ID")) {
+ const char *env_app = getenv("CLIENT_APP_ID");
+ if (env_app) {
app_id = env_app;
}
diff --git a/tests/polkit.py b/tests/polkit.py
index 4afb3b6..bcbddfb 100644
--- a/tests/polkit.py
+++ b/tests/polkit.py
@@ -126,6 +126,13 @@ class Logind:
invocation.return_value(GLib.Variant('(v)', (GLib.Variant('s', '7'),)))
+CTTY_EXEC = (
+ 'import fcntl, os, sys, termios\n'
+ 'os.setsid()\n'
+ 'fcntl.ioctl(0, termios.TIOCSCTTY, 1)\n'
+ 'os.execv(sys.argv[1], sys.argv[1:])\n')
+
+
def spawn(mode=None, terminal_fd=None, **overrides):
env = dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=os.environ['DBUS_SESSION_BUS_ADDRESS'],
WLR_BACKENDS='headless', REDIWM_FORCE_POLKIT='1', XDG_SESSION_ID='test-session', LC_ALL='C', USER='not-the-logged-in-user')
@@ -134,8 +141,10 @@ def spawn(mode=None, terminal_fd=None, **overrides):
env.pop(key, None)
else:
env[key] = value
- # An external setsid avoids Python preexec_fn in a multithreaded fixture.
- command = (['setsid', '--ctty'] if terminal_fd is not None else []) + [sys.argv[1]] + ([mode] if mode else [])
+ # A wrapper that becomes session leader and takes the terminal (what
+ # `setsid --ctty` does, which FreeBSD lacks) avoids Python preexec_fn in a
+ # multithreaded fixture.
+ command = ([sys.executable, '-c', CTTY_EXEC] if terminal_fd is not None else []) + [sys.argv[1]] + ([mode] if mode else [])
return subprocess.Popen(command, env=env,
stdin=subprocess.PIPE if terminal_fd is None else terminal_fd,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0)
@@ -173,6 +182,16 @@ def begin_args(identities=None):
[('unix-user', {'uid': GLib.Variant('u', os.getuid())})])
+def peer_credentials(sock):
+ """(pid, uid) of a unix socket's peer. FreeBSD has no SO_PEERCRED: its
+ LOCAL_PEERCRED is a struct xucred (88 bytes; uid at 4, cr_pid at 80)."""
+ if hasattr(socket, 'SO_PEERCRED'):
+ pid, uid, _ = struct.unpack('3i', sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
+ return pid, uid
+ raw = sock.getsockopt(0, socket.LOCAL_PEERCRED, 88)
+ return struct.unpack_from('i', raw, 80)[0], struct.unpack_from('I', raw, 4)[0]
+
+
class HelperSocket:
"""Independent wire peer. Assert the registering PID also opens the socket."""
def __init__(self, directory, scenario):
@@ -194,7 +213,7 @@ class HelperSocket:
peer, _ = self.listener.accept()
with peer:
peer.settimeout(5)
- pid, uid, _ = struct.unpack('3i', peer.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
+ pid, uid = peer_credentials(peer)
assert pid == self.pid and uid == os.getuid(), (pid, self.pid, uid)
with peer.makefile('rb', buffering=0) as stream:
assert stream.readline() == pwd.getpwuid(os.getuid()).pw_name.encode() + b'\n'
@@ -312,7 +331,9 @@ def terminal_conversations(authority):
with tempfile.TemporaryDirectory(prefix='rediwm-polkit-tty-') as directory:
peer = HelperSocket(directory, 'hold' if cancel else 'success')
master, slave = pty.openpty()
- original = termios.tcgetattr(slave)
+ # Read through the master, which shares the slave's termios: FreeBSD
+ # revokes the slave when the agent, its session leader, exits.
+ original = termios.tcgetattr(master)
start = len(events)
child = spawn(mode='--terminal', terminal_fd=slave, REDIWM_POLKIT_HELPER_SOCKET=peer.path)
peer.pid = child.pid
@@ -335,7 +356,7 @@ def terminal_conversations(authority):
remaining = deadline - time.monotonic()
assert remaining > 0 and select.select([master], [], [], remaining)[0], output
output += os.read(master, 4096)
- assert not termios.tcgetattr(slave)[3] & termios.ECHO
+ assert not termios.tcgetattr(master)[3] & termios.ECHO
if cancel:
child.send_signal(signal.SIGTERM)
else:
@@ -344,9 +365,16 @@ def terminal_conversations(authority):
peer.finish()
logs = stop(child)
# Child has exited; drain the finite amount of remaining tty output.
+ # FreeBSD's master stays readable at EOF once the leader is gone.
while select.select([master], [], [], 0)[0]:
- output += os.read(master, 4096)
- assert termios.tcgetattr(slave) == original
+ try:
+ data = os.read(master, 4096)
+ except OSError:
+ break
+ if not data:
+ break
+ output += data
+ assert termios.tcgetattr(master) == original
assert b'test-response' not in output and 'test-response' not in logs
finally:
if child.poll() is None:
diff --git a/tests/readiness_input.py b/tests/readiness_input.py
index 7b2fff1..991d7f6 100644
--- a/tests/readiness_input.py
+++ b/tests/readiness_input.py
@@ -211,7 +211,7 @@ def main():
sessions.mkdir(parents=True)
for name in ("alpha", "beta"):
(sessions / (name + ".desktop")).write_text(
- f"[Desktop Entry]\nName={name.title()}\nExec=/bin/true\nType=Application\n")
+ f"[Desktop Entry]\nName={name.title()}\nExec=/usr/bin/true\nType=Application\n")
try:
no_input_case(root, share)
nested_case(root, share)
diff --git a/tests/security_context.py b/tests/security_context.py
index 9dd6cdd..0380ee2 100644
--- a/tests/security_context.py
+++ b/tests/security_context.py
@@ -10,10 +10,12 @@ Tests:
6. Sandboxed IPC callers via Flatpak (.flatpak-info) blocked unless allowed, checked per-request.
7. Clean teardown with live sandboxed client.
"""
+import json
import os
from pathlib import Path
import select
import shutil
+import signal
import subprocess
import tempfile
import time
@@ -354,6 +356,43 @@ except Exception as exc:
cmd_malformed = [*bwrap_base, "--ro-bind", str(malformed_info), "/.flatpak-info", "python3", "-c", script, str(ROOT / "tests"), str(tmp)]
r5 = subprocess.run(cmd_malformed, env=session.env, capture_output=True, text=True)
assert "REJECTED" in r5.stdout or r5.returncode != 0, f"malformed flatpak-info should fail closed: {r5.stdout}"
+
+ # 6. The connector exits after handing its socket to a child, so it cannot be
+ # classified: refused. The compositor is stopped while the client runs, so the
+ # connection is accepted after the exit, as a long frame would allow.
+ handoff = """
+import glob, os, socket, sys, time
+tmp, request = sys.argv[1], sys.argv[2].encode()
+ready, go = tmp + "/handoff-ready", tmp + "/handoff-go"
+connector = os.fork()
+if connector == 0:
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s.connect(glob.glob(tmp + "/rediwm-*.sock")[0])
+ if os.fork() == 0:
+ while not os.path.exists(go):
+ time.sleep(0.05)
+ s.sendall(request)
+ time.sleep(1)
+ os._exit(0)
+ os._exit(0)
+os.waitpid(connector, 0)
+open(ready, "w").write("1")
+time.sleep(4)
+"""
+ request = json.dumps({"version": 1, "id": 1, "command": "open_start_menu"}) + "\n"
+ os.kill(session.process.pid, signal.SIGSTOP)
+ try:
+ cmd_handoff = [*bwrap_base, "--ro-bind", str(unallowed_info), "/.flatpak-info", "python3", "-c", handoff, str(tmp), request]
+ p6 = subprocess.Popen(cmd_handoff, env=session.env)
+ wait_for(lambda: (tmp / "handoff-ready").exists(), "handoff client never finished")
+ finally:
+ os.kill(session.process.pid, signal.SIGCONT)
+ time.sleep(0.5)
+ (tmp / "handoff-go").write_text("1")
+ time.sleep(1.0)
+ assert session.ipc.get_shell_state()["start_menu"] is None, "a sandboxed connector that exited must not reach IPC"
+ assert "cannot be checked for a sandbox" in Path(session.log.name).read_text(), "the refusal should be logged"
+ p6.wait(timeout=15)
finally:
session.close()
print("PASS: sandboxed IPC caller detection via Flatpak info and bubblewrap")
diff --git a/tests/startup.py b/tests/startup.py
index 549a430..7d92c70 100644
--- a/tests/startup.py
+++ b/tests/startup.py
@@ -32,7 +32,7 @@ def write_apps(data: Path, count: int = 4):
for index in range(count):
(apps / f"app-{index:02}.desktop").write_text(
f"[Desktop Entry]\nType=Application\nName=App {index:02}\n"
- f"Exec=/bin/true\nIcon=foot\n"
+ f"Exec=/usr/bin/true\nIcon=foot\n"
)
return apps
diff --git a/tests/startup_warmup.py b/tests/startup_warmup.py
index 531bfeb..dcea3e7 100644
--- a/tests/startup_warmup.py
+++ b/tests/startup_warmup.py
@@ -19,7 +19,7 @@ def run(scale):
'height="38"><rect width="38" height="38" fill="red"/></svg>')
(apps / f"app-{index:02}.desktop").write_text(
f"[Desktop Entry]\nType=Application\nName=App {index:02}\n"
- f"Exec=/bin/true\nIcon={icon}\n")
+ f"Exec=/usr/bin/true\nIcon={icon}\n")
process, log = spawn_compositor(tmp, scale=scale, outputs="2", env_extra={
"XDG_DATA_HOME": str(data), "XDG_DATA_DIRS": str(tmp / "empty"),
})
diff --git a/tests/window_tabs.py b/tests/window_tabs.py
index cc08d61..d651f6d 100644
--- a/tests/window_tabs.py
+++ b/tests/window_tabs.py
@@ -259,7 +259,7 @@ def run():
# A normal launch command that exits without a new surface must
# clear pending feedback and leave the group untouched.
desktop = apps / "tab-fixture.desktop"
- desktop.write_text('[Desktop Entry]\nType=Application\nName=Tab fixture\nExec=/bin/true\n')
+ desktop.write_text('[Desktop Entry]\nType=Application\nName=Tab fixture\nExec=/usr/bin/true\n')
click(separate, "tab_new")
wait_for(lambda: not next(w for w in widgets(separate) if w["name"] == "tab_new")["is_disabled"], "failed launch clears pending", timeout=15)
assert len(windows()) == 3
diff --git a/tools/freebsd-probe/login-probe.sh b/tools/freebsd-probe/login-probe.sh
new file mode 100755
index 0000000..91e5948
--- /dev/null
+++ b/tools/freebsd-probe/login-probe.sh
@@ -0,0 +1,92 @@
+#!/bin/sh
+# Probe of FreeBSD's login and seat stack for RediWM (docs/plans/freebsd.md,
+# "Login and seat"). It only reads: packages, services, PAM stacks, devices,
+# ConsoleKit2's D-Bus interfaces and what polkit says about this shell. A bus
+# call may start a service that is installed but not running, which is part of
+# the answer. It writes one report; send that file back.
+#
+# Run it from a console login (not ssh) as the user who will run RediWM:
+#
+# sh tools/freebsd-probe/login-probe.sh [report-file] # ./login-probe.txt
+
+report=${1:-login-probe.txt}
+ck=org.freedesktop.ConsoleKit
+ck_manager=/org/freedesktop/ConsoleKit/Manager
+
+section() { printf '\n==== %s ====\n' "$*" >> "$report"; }
+
+# One command, its output and exit status; a missing tool is a finding too.
+run() {
+ printf '\n$ %s\n' "$*" >> "$report"
+ if command -v "$1" > /dev/null 2>&1; then
+ "$@" >> "$report" 2>&1
+ printf '[exit %s]\n' "$?" >> "$report"
+ else
+ printf '[%s not installed]\n' "$1" >> "$report"
+ fi
+}
+
+bus() { # bus DEST PATH MEMBER [ARG...]: a system bus method call
+ dest=$1 path=$2 member=$3
+ shift 3
+ run dbus-send --system --print-reply --dest="$dest" "$path" "$member" "$@"
+}
+
+main() {
+ section "who and where"
+ run uname -srm
+ run id
+ run tty
+ # Only the session variables, never the whole environment.
+ printf '\n$ env (XDG_*, DBUS_*)\n' >> "$report"
+ env | grep -E '^(XDG_|DBUS_)' | sort >> "$report" 2>&1
+ if [ -n "$XDG_RUNTIME_DIR" ]; then run ls -ld "$XDG_RUNTIME_DIR"; fi
+
+ section "packages and services"
+ run pkg info -x '^(seatd|consolekit|dbus|polkit|pam_xdg|libudev|libinput|wlroots|drm-kmod|gpu-firmware)'
+ run service -e
+ run pgrep -lf 'seatd|dbus-daemon|console-kit|polkitd|powerd'
+
+ section "seat: seatd, devices, console"
+ run ls -l /var/run/seatd.sock /run/seatd.sock
+ run getent group seatd video
+ run kldstat
+ run ls -l /dev/dri /dev/input /dev/console /dev/ttyv0
+ run sysctl kern.vty kern.evdev.rcpt_mask hw.acpi.supported_sleep_state hw.acpi.lid_switch_state
+
+ section "PAM"
+ run grep -n '^session' /etc/pam.d/login
+ run sh -c "grep -n -E 'pam_(ck_connector|xdg|systemd)' /etc/pam.d/* /usr/local/etc/pam.d/*"
+
+ section "ConsoleKit2: sessions and interfaces"
+ run ck-list-sessions
+ bus org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.ListNames
+ bus "$ck" "$ck_manager" org.freedesktop.DBus.Introspectable.Introspect
+ bus "$ck" "$ck_manager" "$ck.Manager.GetSessionForUnixProcess" uint32:$$
+ bus "$ck" "$ck_manager" "$ck.Manager.GetCurrentSession"
+
+ session=$(dbus-send --system --print-reply --dest="$ck" "$ck_manager" \
+ "$ck.Manager.GetSessionForUnixProcess" uint32:$$ 2> /dev/null |
+ sed -n 's/.*object path "\(.*\)"/\1/p')
+ if [ -n "$session" ]; then
+ section "ConsoleKit2: this shell's session ($session)"
+ bus "$ck" "$session" org.freedesktop.DBus.Introspectable.Introspect
+ for member in GetId GetSeatId GetSessionType GetUnixUser IsLocal IsActive \
+ GetDisplayDevice GetX11Display GetRemoteHostName GetLockedHint; do
+ bus "$ck" "$session" "$ck.Session.$member"
+ done
+ else
+ section "ConsoleKit2: no session for this shell"
+ fi
+
+ section "polkit (no -u, so it cannot prompt)"
+ run pkaction --version
+ run pkcheck --action-id org.freedesktop.policykit.exec --process $$
+}
+
+if ! : > "$report"; then
+ echo "login-probe: cannot write $report" >&2
+else
+ main
+ echo "login-probe: wrote $report"
+fi