Skip to content

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

Prepare the FreeBSD port: platform parts, libc translate root, build fixes

oxydizer75c60972a551
diff --git a/AGENTS.md b/AGENTS.md
index 9590359..47d3067 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -266,13 +266,16 @@ panel painting. The key rules:
compositor imports). Parsing/persistence is `config/`, applying and reloads
`config_runtime/`, shared raster code (`text`, `anim`, `sdf`, icons) `ui/`.
`memory` owns the process allocator; executables own its shutdown.
-* **OS calls go through `src/platform/`**: use it, not `pidfd_*`, `inotify_*`
- or `/proc/self/exe` (C and C++: its `child.h`, `self_exe.h`).
+* **OS calls go through `src/platform/`**: use it, not `pidfd_*`, `inotify_*`,
+ `SO_PEERCRED`, `prctl`, `eventfd` flags or `/proc/self/exe` (C and C++: its
+ `child.h`, `self_exe.h`, `peer.h`, `process.h`). Elsewhere call libc or
+ `std.posix`, not `std.os.linux` (its `AGENTS.md` lists the exceptions).
* Zig 0.17 has no `@cImport`: the build translates header roots in `src/c/`
into modules (`support.cHeaders`): `c` (libc), `c_gfx` (libc, cairo,
freetype, harfbuzz, fontconfig, xkbcommon), `c_pulse`, `c_libinput`,
`c_png`, `c_archive`. Add a header to its root; a module links nothing, so
- artifacts link their libraries. The roots undefine `_FORTIFY_SOURCE`
+ artifacts link their libraries. A header that exists on one OS only goes
+ under `#ifdef __linux__` (or `__FreeBSD__`) at the end of `libc.h`. The roots undefine `_FORTIFY_SOURCE`
(fortified wrappers break translate-c in ReleaseSafe) and define
`_GNU_SOURCE`, so socket calls take `.{ .__sockaddr__ = @ptrCast(&addr) }`.
Never translate glib/gobject/gio/librsvg; hand-declare the ABI. No runtime
diff --git a/build.zig b/build.zig
index 19dda27..cc2108c 100644
--- a/build.zig
+++ b/build.zig
@@ -216,7 +216,10 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
.use_llvm = use_llvm,
.wlroots_prefix = wlroots_prefix,
- .transfers = b.option(bool, "transfers", "Build and install the torrent transfers helper") orelse true,
+ // Files hides Transfers (src/files/app_torrents.zig `enabled`), so the helper is
+ // unused for now. Off on FreeBSD, where its libtorrent, glib and peer-credential
+ // code is not ported (docs/plans/freebsd.md).
+ .transfers = b.option(bool, "transfers", "Build and install the torrent transfers helper (default: on, except on FreeBSD)") orelse (target.result.os.tag != .freebsd),
.i18n_tool = i18n_tool,
.wayland = wayland,
.xkbcommon = xkbcommon,
diff --git a/build/apps.zig b/build/apps.zig
index 0fc0372..314655c 100644
--- a/build/apps.zig
+++ b/build/apps.zig
@@ -55,9 +55,11 @@ pub fn add(ctx: Context) Apps {
);
b.getInstallStep().dependOn(&install_files.step);
b.getInstallStep().dependOn(&install_files_desktop_entry.step);
- const install_files_icon = b.addSystemCommand(&.{ "install", "-Dm644", "-t" });
- install_files_icon.addDirectoryArg(support.installed(.prefix, "share/icons/hicolor/256x256/apps"));
- install_files_icon.addFileArg(b.path("assets/icons/redi-fm-icon.png"));
+ const install_files_icon = b.addInstallFileWithDir(
+ b.path("assets/icons/redi-fm-icon.png"),
+ .prefix,
+ "share/icons/hicolor/256x256/apps/redi-fm-icon.png",
+ );
b.getInstallStep().dependOn(&install_files_icon.step);
// rediwm-files links neither wlroots-server nor libinput/libpulse, so it
// can be built (and its dependencies checked) without the rest of this
@@ -80,6 +82,7 @@ pub fn add(ctx: Context) Apps {
inline for (.{ "helper.cpp", "helper_transfers.cpp", "helper_peers.cpp", "helper_tray.cpp" }) |part| torrents.addFileArg(b.path("src/files/torrent/" ++ part));
torrents.addFileInput(b.path("src/files/torrent/helper.hpp"));
torrents.addFileInput(b.path("src/platform/self_exe.h"));
+ torrents.addFileInput(b.path("src/platform/peer.h"));
torrents.addArg("-o");
const torrent_binary = torrents.addOutputFileArg("rediwm-transfers");
const install_torrents = b.addInstallFileWithDir(torrent_binary, .bin, "rediwm-transfers");
@@ -91,12 +94,10 @@ pub fn add(ctx: Context) Apps {
const transfers_entry = b.addInstallFileWithDir(localizedData(b, i18n_tool, ctx.layout.prefix, "data/rediwm-transfers.desktop"), .prefix, "share/applications/rediwm-transfers.desktop");
b.getInstallStep().dependOn(&transfers_entry.step);
files_step.dependOn(&transfers_entry.step);
- const test_torrents = b.step("test-files-torrents", "Test real loopback transfers and the Files/tray interface");
+ const test_torrents = b.step("test-files-torrents", "Test real loopback transfers");
const torrent_engine_test = b.addSystemCommand(&.{ "python3", "tests/files_torrents.py" });
torrent_engine_test.step.dependOn(b.getInstallStep());
- const torrent_ui_test = b.addSystemCommand(&.{ "python3", "tests/files_transfers_ui.py" });
- torrent_ui_test.step.dependOn(&torrent_engine_test.step);
- test_torrents.dependOn(&torrent_ui_test.step);
+ test_torrents.dependOn(&torrent_engine_test.step);
}
files_step.dependOn(&install_files_desktop_entry.step);
files_step.dependOn(&terminal_license.step);
diff --git a/build/data.zig b/build/data.zig
index f53a2a5..f643096 100644
--- a/build/data.zig
+++ b/build/data.zig
@@ -68,7 +68,8 @@ pub fn add(ctx: Context) void {
cursorgen_run.addDirectoryArg(b.path("assets/cursors"));
const cursor_themes = cursorgen_run.addOutputDirectoryArg("icons");
// Cursor aliases are symlinks, which InstallDir drops; cp -a keeps them.
- const install_cursors = b.addSystemCommand(&.{ "sh", "-c", "mkdir -p \"$2\" && cp -a -T \"$1\" \"$2\"", "sh" });
+ // "$1/." copies the contents into the existing "$2" with GNU and BSD cp (-T is GNU only).
+ const install_cursors = b.addSystemCommand(&.{ "sh", "-c", "mkdir -p \"$2\" && cp -a \"$1/.\" \"$2\"", "sh" });
install_cursors.addDirectoryArg(cursor_themes);
install_cursors.addDirectoryArg(support.installed(.prefix, "share/icons"));
b.getInstallStep().dependOn(&install_cursors.step);
diff --git a/build/session.zig b/build/session.zig
index 090a7da..ba20001 100644
--- a/build/session.zig
+++ b/build/session.zig
@@ -45,6 +45,7 @@ pub fn add(ctx: Context) Session {
.use_lld = use_llvm,
});
restart.root_module.addImport("install_paths", ctx.layout.options);
+ restart.root_module.addImport("platform", ctx.platform_mod);
b.installArtifact(restart);
const dm_ipc_mod = b.createModule(.{
diff --git a/docs/plans/freebsd.md b/docs/plans/freebsd.md
index ea25d63..266f59f 100644
--- a/docs/plans/freebsd.md
+++ b/docs/plans/freebsd.md
@@ -1,79 +1,87 @@
# FreeBSD support plan
-Status: draft, 2026-10-31. Preparation steps P.1–P.3 and P.7 are done (Linux
-only, `src/platform/` and the call sites); nothing else is implemented.
-Decisions D1–D6 are open.
+Status: draft, 2026-11-05. The Linux-side preparation (P.1–P.4, P.7–P.10) is
+done, P.5 and P.6 are open, and no FreeBSD code exists yet. Decisions D1–D6
+are open.
-Run RediWM on FreeBSD: first the compositor in a seatd session on DRM, then
-the shell features and apps, and last `rediwm-dm` and packaging. Linux stays
-the primary platform; the port must not change Linux behaviour or cost.
+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, and its session,
-DRM, libinput and udev layers (libseat + seatd, drm-kmod, libinput over
-evdev, libudev-devd) are exactly what makes a compositor port cheap. Mesa
-EGL/GLES, Xwayland, cairo, freetype, harfbuzz, fontconfig, librsvg, gio,
-CUPS, libarchive, libtorrent, D-Bus, polkit, xdg-desktop-portal and
-pulseaudio are in ports; OpenPAM covers `pam_appl.h`. Zig 0.17 targets
+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 is the problem: it has no OS abstraction at all (no
-`builtin.os.tag` test anywhere). The Linux assumptions sit at four levels.
-
-### 1. Compile barrier
-
-`src/c/libc.h` includes `linux/netlink.h`, `sys/prctl.h` and `sys/eventfd.h`
-(`sys/inotify.h` left with P.2), so the `c` module, and with it every artifact, fails to
-translate. About 47 Zig files call `std.os.linux.*` directly.
-
-| Linux interface | Users | FreeBSD |
+Our own code had no OS abstraction. Its Linux half now lives in
+`src/platform/` (child handles, file watching, own path, peer credentials,
+process attributes, wake descriptors, seccomp filters, tool lookup, with C
+headers beside it), and only 22 files still use `std.os.linux` outside it.
+What is left is the FreeBSD half of each part, 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 is fixed on the
+Linux side (P.8–P.10; the transfers helper is off by default on FreeBSD).
+On 15.1 `sys/inotify.h`, `sys/timerfd.h`, `sys/eventfd.h` and `cr_pid` in
+`sys/ucred.h` exist (header checks only). Not known yet: what the Zig code
+behind `c` needs now that it translates, `memfd_create`, the transfers
+helper's C++ flags under clang and libc++, and whether a DRM session or the
+headless GLES2 path works.
+
+### Interfaces still to port
+
+| Linux interface | Where | FreeBSD |
| --- | --- | --- |
-| `eventfd` | ~38 files | Native (13+). Swap `linux.EFD` for `c.EFD_*`. |
-| `memfd_create`, `timerfd` | few | Native on current releases (confirm in phase 0). |
-| `pidfd_open`, `pidfd_send_signal`, `waitid(P_PIDFD)` | `platform/child.zig` (`Handle`, `Set`) and `platform/child.h`, used by `session/child.zig`, the supervisor, dm worker and daemon, IPC, `Toplevel`, the pickers, System Monitor and the terminal engine | No equivalent for an existing pid. kqueue `EVFILT_PROC`/`NOTE_EXIT`; the kqueue fd joins the wl event loop like a pidfd. Signals by pid, guarded by the still-unreaped zombie, which only holds for our own children: handles on other processes (`Toplevel` client pids, `Handle.peer` for IPC, System Monitor) become a bare pid with a reuse race, so those callers need another identity check (start time from `kern.proc`). `Handle.pid()` reads `fdinfo` and has no counterpart. `Pid`/`Signal` are `std.os.linux` types today; switch them to `std.posix` before the FreeBSD part. |
-| `signalfd`, `epoll` | supervisor, dm daemon/worker, `platform.child.Set` | kqueue `EVFILT_SIGNAL`, kqueue. |
-| `inotify` | `platform/watch.zig` (`Watcher`); all 7 users (config, desktop, Files worker ×2, printing, start menu, system monitor settings) call it | Native in 15.0 (confirm); otherwise kqueue `EVFILT_VNODE`, which has no names: diff the directory to synthesize them. |
-| `prctl` | dm worker, lock, PAM worker, PDF print/sandbox, theme helper | `procctl(PROC_PDEATHSIG_CTL / PROC_NO_NEW_PRIVS_CTL / PROC_TRACE_CTL)`, `pthread_set_name_np`. |
-| `statx`, `getdents64` | Files dirsize/properties, supervisor, session restart, IPC | `fstatat`, `getdirentries` or `std.Io.Dir`. |
-| raw `linux.fork/execve/wait4/exit_group/close/read` | many | libc. Note the `-errno` vs `errno` convention change. |
-| `SO_PEERCRED` | IPC peer checks (4 files) | `getpeereid` / `LOCAL_PEERCRED`. Security-relevant: sandbox allowances need the peer pid; confirm `cr_pid`. |
-| `/proc/self/exe` | `platform/exe.zig` and `platform/self_exe.h` (Zig sites, `bass.c`, torrent helper; dm re-execs through `exe.execSelf`) | `sysctl KERN_PROC_PATHNAME` / `std.process.executablePath`; `fexecve` on a descriptor opened at startup for the re-exec. |
-| `/proc/self/fd`, `fdinfo` | spawn paths | `closefrom`/`close_range`. |
-| `/proc/<pid>/stat`, `/proc/stat`, `/proc/meminfo`, task children | system monitor, `ipc/processes.zig` | libprocstat / `kern.proc` sysctls behind a collector backend. |
+| pidfd (`platform.child` `Handle`, `Set`; `child.h`) | `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; on 14.x kqueue `EVFILT_VNODE` has no names, so diff the directory. |
+| `eventfd` (`platform.wake`) | 9 sites | Native (13+); the flag values differ. |
+| `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`. |
+| `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`. 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` / `std.process.executablePath`; `fexecve` on a descriptor opened at startup for the re-exec. |
+| `statx`, `getdents64`, `dirent64` | Files folder sizes, IPC socket check, `session_restart` | `fstatat`, `getdirentries` or `std.Io.Dir`, behind a `platform` function. |
+| `/proc/self/fd`, `fdinfo` | spawn paths; fd-as-path opens in `files/properties`, `pdf/print.c`, `pdf/sandbox.c`, `files/terminal/child.c` | `closefrom` for spawn paths; the path form needs `fdescfs` or `*at` calls on the fd, per site. |
+| `/proc/<pid>/…`, `/proc/stat`, `/proc/meminfo` | system monitor, `ipc/processes.zig`, `placeholder_match` (parent chain), `session_restart` (exe), `detectSandbox` (`root/.flatpak-info`; no Flatpak on FreeBSD, expect "not sandboxed"), editor memory probe, supervisor teardown tree | libprocstat / `kern.proc` sysctls behind a collector backend (P.6); `KERN_PROC_PATHNAME` takes a pid. procfs is optional on FreeBSD. |
| `pty.h` | terminal engine | `libutil.h` (`openpty`/`forkpty`), link `util`. |
-| `renameat2` | ~9 sites: Files ops, Editor, Images, screenshots, desktop watcher, theme helper, torrent helper | Emulate no-replace with `link` + `unlink`, behind one `platform` function. |
-| `DRM_IOCTL_VERSION` via `linux.IOCTL` | `Output.zig:206` | Different ioctl encoding: use libdrm `drmGetVersion`. |
-| netlink `KOBJECT_UEVENT` | printer hotplug | devd's seqpacket socket, or rescans only. |
+| `renameat2` | ~9 sites: Files ops, Editor, Images, screenshots, desktop watcher, theme helper, torrent helper | `link` + `unlink` for no-replace, behind one `platform` function. |
+| `DRM_IOCTL_VERSION` | `Output.zig` | libdrm `drmGetVersion`. |
+| netlink `KOBJECT_UEVENT` | printer hotplug (`printing/client.zig`) | devd's seqpacket socket, or rescans only. |
+| `gettid`; `fork`, `kill`, `wait4`, `poll` loops | `thumbs`; supervisor and dm | A `platform` wrapper; the loops are replaced in phases 2 and 4. |
-### 2. Sandboxes
+### 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.
+(`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.
-### 3. System services
+### 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". |
-| Brightness | `brightnessctl` | `backlight(8)` (or own code, see preparation). |
+| 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`. |
-| Sounds, terminals, `pkexec`, polkit socket | `/usr/bin/...`, `/run/polkit/...` | Ports live under `/usr/local`; search `PATH` instead of fixed paths. |
| Audio | libpulse; PipeWire for the bass DSP | pulseaudio or pipewire-pulse; the DSP is optional. |
-### 4. 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
@@ -82,90 +90,104 @@ numbers), PDEATHSIG, signalfd, pidfd. On FreeBSD `XDG_RUNTIME_DIR` comes from
enabled by the installer, so the port ships without it first (D2): start from
the console through seatd, or from greetd.
+### 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.
+
## Rules for the port
* **One platform module.** `src/platform/` (named module, no compositor
- imports) owns child watching, signal sources, file watching, process
- control, own-executable path, peer credentials 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.
-* **Translate roots per OS.** `src/c/libc.h` keeps portable headers;
- Linux-only ones move to a root only Linux builds translate.
-* **Missing services hide, never fake.** A feature without a backend is
- absent from the taskbar and Settings, as on a Linux machine lacking it.
-* **Fail closed.** No sandbox, no sandboxed app; no peer pid, no IPC
- allowance.
+ 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.
+* **Missing services hide, never fake.** A feature without a backend is absent
+ from the taskbar and Settings, as on a Linux machine lacking it.
+* **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).
+* 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)
-Refactors that are worth doing for Linux alone and shrink the port. Each
-lands separately, keeps behaviour, and is checked with the usual Debug,
-ReleaseSafe, `zig build test` and affected integration suites.
-
-1. **Child watching** (done): the ad hoc pidfd sites and `child_set.zig` are
- now `platform.child` (`Handle`, `Set`, `reap`) with `session/child.zig` as
- the Wayland-loop adapter and `platform/child.h` for the terminal engine.
- The port reimplements that module, not ten call sites. Left for P.4: plain
- `kill`/`wait4`, the supervisor's `signalfd`/`epoll`, and the `/proc` walks.
-2. **File watching** (done): `platform.watch.Watcher` for the 7 inotify users,
- with event parsing in one place and `sys/inotify.h` out of `libc.h`.
-3. **Own executable** (done): `platform.exe` and `self_exe.h` for the 11
- `/proc/self/exe` readers.
-4. **Raw syscalls to libc** where libc has the call (fork, execve, wait4,
- close, read, getuid, …), keeping `std.os.linux` for what has no libc form.
-5. **One sandbox interface:** (syscall filters done) the PDF sandbox no longer
- uses libseccomp: `platform/seccomp.zig` builds and loads the filter and
- `pdf/syscall_policy.zig` holds its allow-list, checked verdict for verdict
- against the libseccomp program it replaced; the theme helper's filter
- (`theme_helper/syscall_policy.zig`: no `socket`/`connect`) uses the same
- builder, checked the same way against its old C filter. Left: give both
- sandboxes 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 the entry point promises before moving either.
-6. **Process listing:** keep `/proc` parsing behind the system monitor's
- collector interface (shared with `ipc/processes.zig`).
-7. **Paths** (done): no fixed `/usr/bin/…` tool path is left in the shell.
- `paplay` is found on `PATH` (`config.app_theme.executable`) and `locale` is
- spawned by bare name, which `std.process.spawn` resolves on `PATH`. The
- programs that run as root or are handed a secret (`pkexec`, `systemctl`)
- deliberately do not use `PATH`: `platform.tool.system` searches only
- `/usr/bin`, `/bin` and `/usr/local/bin`, so a user-writable `PATH` entry
- cannot capture a password typed in Settings. Left as they are: the accounts
- helper's candidate lists (root; phase 3 rewrites it on `pw(8)`), the
- `/bin/sh` launches (present on both systems) and the polkit agent helper's
- directory list in `polkit/native.c` (add `/usr/local/lib/polkit-1` and
- `/usr/local/libexec` in phase 1; it is verified setuid and root-owned), and
- the cupsd probe in `printing/platform.zig` (`usr/local/sbin`, phase 3).
-
-Steps 1–3 and 7 were small; 4 is mechanical but broad; 5 is security work and
-needs its own review.
+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.
+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.
+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:
+
+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.
+6. **Process listing:** `/proc` parsing behind the system monitor's collector
+ interface (shared with `ipc/processes.zig`); every `/proc` reader in the
+ table needs a `platform` or collector entry point.
+7. **Paths left:** the fixed `/etc` and `/run` paths (`/etc/rediwm/dm.conf` and
+ `greeter.toml`, `/etc/pam.d/rediwm*`, `/etc/xdg`, `/etc/cups/client.conf`,
+ `/run/polkit/agent-helper.socket`, `/run/rediwm-dm/`) want a sysconfdir and
+ rundir option (`/usr/local/etc`); the polkit helper's directory list
+ (`polkit/native.c`) needs `/usr/local/lib/polkit-1` and
+ `/usr/local/libexec` (phase 1); the cupsd probe (`printing/platform.zig`)
+ needs `/usr/local/sbin` and the accounts helper's candidate lists need
+ `pw(8)` (phase 3); `/etc/login.defs` (two places) has no FreeBSD
+ counterpart (`login.conf`).
+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
-above exist on the target release(s) (D1), and whether the integration tests'
-headless + GLES2 path works there.
+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
Split `src/platform/` into Linux and FreeBSD parts (`exe.path` can use
-`std.process.executablePath`, which already reads `kern.proc.pathname`);
-split the translate roots; build conditions for `util`, `pam`, and for
-`platform/seccomp.zig`, which is Linux-only code now that nothing links
-libseccomp. Hide NM, BlueZ, PPD, UDisks, app scopes; PDF and theme helper
-refuse. Goal: `rediwm` and the apps start in a seatd session and the headless
-integration suites run.
+`std.process.executablePath`, which already reads `kern.proc.pathname`); build
+conditions for `util`, `pam`, and for `platform/seccomp.zig`, which is
+Linux-only code. Hide NM, BlueZ, PPD, UDisks, app scopes; PDF and theme helper
+refuse. 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.
### 2. Real session
@@ -181,14 +203,14 @@ qualification for Files DEVICES.
### 4. Login manager and packaging
-`rediwm-dm` on OpenPAM, `pam_xdg`, seatd and `vt(4)`; `install.sh` `pkg`
-path; release tarball or a port (D6); FreeBSD in `make-release.sh`
-verification.
+`rediwm-dm` on OpenPAM, `pam_xdg`, seatd and `vt(4)`; `install.sh` `pkg` path;
+release tarball or a port (D6); FreeBSD in `make-release.sh` verification.
## Decisions
* **D1 Target release:** 15.x only (native inotify, timerfd) or 14.x too
- (kqueue vnode watching, more fallbacks). Recommend 15.x only.
+ (kqueue vnode watching, more fallbacks). Recommend 15.x only; 15.1 has the
+ headers (see above).
* **D2 DM in the first release:** recommend no.
* **D3 Network:** hide, or a wpa_supplicant control-socket backend later.
Recommend hide.
@@ -196,14 +218,27 @@ verification.
closed) or allow with a warning.
* **D5 Power backend:** ConsoleKit2, or our own polkit-gated helper calling
`shutdown`/`acpiconf`. Recommend ConsoleKit2.
-* **D6 Distribution:** prebuilt tarball like the Linux releases, or a port
- in `x11-wm`. Decide after phase 2.
+* **D6 Distribution:** prebuilt tarball like the Linux releases, or a port in
+ `x11-wm`. Decide after phase 2.
## 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
-ReleaseSafe `rediwm` on both after touching environment handling. Sandbox
-work (P5, phase 3) gets a dedicated escape test per helper: path opens,
-sockets and exec are denied.
+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.
diff --git a/src/c/libc.h b/src/c/libc.h
index cc3bdcf..f9b9876 100644
--- a/src/c/libc.h
+++ b/src/c/libc.h
@@ -1,5 +1,6 @@
-/* The libc and Linux headers Zig code uses, translated once into the `c`
- * module (build/support.zig). Zig 0.17 has no @cImport.
+/* The libc headers Zig code uses, translated once into the `c` module
+ * (build/support.zig). Zig 0.17 has no @cImport. Headers that exist on one OS
+ * only sit under #ifdef at the end, so one root serves Linux and FreeBSD.
*
* Translate libc declarations, not glibc's fortified inline wrappers: Zig
* rejects their attribute(error) calls in ReleaseSafe. This affects the
@@ -13,7 +14,6 @@
#include <fnmatch.h>
#include <grp.h>
#include <langinfo.h>
-#include <linux/netlink.h>
#include <locale.h>
#include <monetary.h>
#include <poll.h>
@@ -27,10 +27,13 @@
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
-#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
+
+#ifdef __linux__
+#include <linux/netlink.h> /* printer hotplug uevents */
+#endif
diff --git a/src/config_runtime/app_theme.zig b/src/config_runtime/app_theme.zig
index 2074248..996d90c 100644
--- a/src/config_runtime/app_theme.zig
+++ b/src/config_runtime/app_theme.zig
@@ -1,6 +1,7 @@
//! Filesystem work runs only on an explicit Settings action. One eventfd
//! wakes the compositor when the export finishes; there are no idle timers.
const std = @import("std");
+const platform = @import("platform");
const config = @import("config").app_theme;
const c = std.posix.system;
const a = std.heap.c_allocator;
@@ -17,8 +18,7 @@ pub const Job = struct {
pub fn create(io: std.Io, env: std.process.Environ, toolkit: config.Toolkit, palette: config.Palette) !*Job {
const self = try a.create(Job);
errdefer a.destroy(self);
- const fd = c.eventfd(0, @intCast(std.os.linux.EFD.CLOEXEC | std.os.linux.EFD.NONBLOCK));
- if (fd < 0) return error.EventFdFailed;
+ const fd = platform.wake.create() orelse return error.EventFdFailed;
self.* = .{ .io = io, .env = env, .toolkit = toolkit, .palette = palette, .fd = fd };
return self;
}
diff --git a/src/config_runtime/theme_job.zig b/src/config_runtime/theme_job.zig
index 935e77f..55465ea 100644
--- a/src/config_runtime/theme_job.zig
+++ b/src/config_runtime/theme_job.zig
@@ -1,5 +1,6 @@
//! Helper jobs wake once by eventfd; no archive/image work on the event loop.
const std = @import("std");
+const platform = @import("platform");
const Server = @import("../Server.zig");
const wl = @import("wayland").server.wl;
const protocol = @import("../ipc/protocol.zig");
@@ -52,8 +53,7 @@ pub fn start(server: *Server, args: []const []const u8, client: ?*Client, id: ?p
for (args, argv[1..]) |arg, *dst| dst.* = try mem.dupe(u8, arg);
var env = try server.environ.createMap(a);
errdefer env.deinit();
- const fd = c.eventfd(0, @intCast(std.os.linux.EFD.CLOEXEC | std.os.linux.EFD.NONBLOCK));
- if (fd < 0) return error.EventFdFailed;
+ const fd = platform.wake.create() orelse return error.EventFdFailed;
errdefer _ = c.close(fd);
const job = try a.create(Job);
errdefer a.destroy(job);
diff --git a/src/desktop/embedded.zig b/src/desktop/embedded.zig
index 82ef017..f88fd58 100644
--- a/src/desktop/embedded.zig
+++ b/src/desktop/embedded.zig
@@ -11,6 +11,7 @@
//! and wakes for worker results, deadlines and animation frames; an idle
//! desktop arms no timer.
const std = @import("std");
+const platform = @import("platform");
const wl = @import("wayland").server.wl;
const wlr = @import("wlroots");
const sn = @import("../node.zig");
@@ -672,9 +673,7 @@ pub const Desktop = struct {
for (self.worker.takeStarted(&started)) |*launch| {
app_scope.place(self.server, launch.pid, launch.app());
_ = @import("../session/child.zig").watch(a, self.server.wl_server.getEventLoop(), launch.pid, null, null) catch {
- _ = std.os.linux.kill(launch.pid, .KILL);
- var status: u32 = 0;
- while (std.os.linux.errno(std.os.linux.wait4(launch.pid, @ptrCast(&status), 0, null)) == .INTR) {}
+ platform.child.killAndReap(launch.pid);
};
}
}
diff --git a/src/desktop/watcher.zig b/src/desktop/watcher.zig
index 5012d3f..d4cfd3f 100644
--- a/src/desktop/watcher.zig
+++ b/src/desktop/watcher.zig
@@ -139,8 +139,7 @@ pub const Worker = struct {
pub fn deinit(self: *Worker) void {
self.stopAndJoin();
for (self.started[0..self.started_len]) |launch| {
- var status: u32 = 0;
- _ = std.os.linux.wait4(launch.pid, @ptrCast(&status), std.os.linux.W.NOHANG, null);
+ _ = platform.child.reap(launch.pid);
}
if (self.wake_worker >= 0) _ = c.close(self.wake_worker);
if (self.wake_main >= 0) _ = c.close(self.wake_main);
diff --git a/src/dm/worker.zig b/src/dm/worker.zig
index 9d15dfc..2c85e82 100644
--- a/src/dm/worker.zig
+++ b/src/dm/worker.zig
@@ -37,7 +37,7 @@ fn report(fd: c_int, tag: proto.Report, text: []const u8) void {
}
pub fn runWorker(ctrl_fd: c_int, greeter_fd: c_int, confdir: ?[]const u8, is_test: bool) !u8 {
- _ = c.prctl(c.PR_SET_PDEATHSIG, @as(c_ulong, @intFromEnum(linux.SIG.TERM)), @as(c_ulong, 0), @as(c_ulong, 0), @as(c_ulong, 0));
+ platform.process.dieWithParent(.TERM);
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
@@ -274,7 +274,7 @@ fn execSession(
// Nothing the greeter runs needs to gain privileges (power actions
// ask logind over D-Bus), so no setuid/file-capability exec may.
// User sessions keep them for sudo and pkexec.
- if (c.prctl(c.PR_SET_NO_NEW_PRIVS, @as(c_ulong, 1), @as(c_ulong, 0), @as(c_ulong, 0), @as(c_ulong, 0)) != 0) linux.exit_group(1);
+ platform.process.noNewPrivileges() catch linux.exit_group(1);
const cmd = a.dupeSentinel(u8, exec, 0) catch linux.exit_group(1);
const argv = [_:null]?[*:0]const u8{ "/bin/sh", "-c", cmd.ptr };
_ = linux.execve("/bin/sh", &argv, env.ptr);
diff --git a/src/files/terminal/bash.c b/src/files/terminal/bash.c
index 7300992..0bb77e4 100644
--- a/src/files/terminal/bash.c
+++ b/src/files/terminal/bash.c
@@ -14,6 +14,7 @@
#include <sys/socket.h>
#include <readline/readline.h>
#include "protocol.h"
+#include "../../platform/peer.h"
#ifndef RL_STATE_READSTR
#define RL_STATE_READSTR 0
#endif
@@ -143,10 +144,10 @@ static int terminal_builtin(WordList *args) {
return 0;
}
if (channel >= 0) return 0;
- struct ucred peer;
- socklen_t len = sizeof peer;
- if (getsockopt(3, SOL_SOCKET, SO_PEERCRED, &peer, &len) ||
- peer.uid != getuid() || peer.pid != getppid()) return 1;
+ uid_t uid;
+ pid_t pid;
+ if (rediwm_peer_credentials(3, &uid, &pid) ||
+ uid != getuid() || pid != getppid()) return 1;
channel = fcntl(3, F_DUPFD_CLOEXEC, 10);
close(3);
if (channel < 0) return 1;
diff --git a/src/files/torrent/helper_peers.cpp b/src/files/torrent/helper_peers.cpp
index 808770a..f7ae719 100644
--- a/src/files/torrent/helper_peers.cpp
+++ b/src/files/torrent/helper_peers.cpp
@@ -1,6 +1,7 @@
// The Files windows that subscribe: JSON snapshots out, commands in.
// Part of rediwm-transfers (helper.cpp).
#include "helper.hpp"
+#include "../../platform/peer.h"
namespace helper {
@@ -141,11 +142,9 @@ gboolean accept_peer(gint fd, GIOCondition, gpointer) {
int client = accept4(fd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (client < 0)
return G_SOURCE_CONTINUE;
- struct ucred cred{};
- socklen_t size = sizeof cred;
- if (peers.size() >= 32 ||
- getsockopt(client, SOL_SOCKET, SO_PEERCRED, &cred, &size) ||
- cred.uid != getuid()) {
+ uid_t uid = 0;
+ if (peers.size() >= 32 || rediwm_peer_credentials(client, &uid, nullptr) ||
+ uid != getuid()) {
close(client);
return G_SOURCE_CONTINUE;
}
diff --git a/src/files/torrents.zig b/src/files/torrents.zig
index 129952f..fbe4f59 100644
--- a/src/files/torrents.zig
+++ b/src/files/torrents.zig
@@ -2,6 +2,7 @@
const std = @import("std");
const tr = @import("i18n").tr;
const c = @import("c");
+const platform = @import("platform");
pub const File = struct { index: usize, path: []const u8, size: i64 };
pub const Transfer = struct {
source: []const u8 = "",
@@ -67,9 +68,8 @@ pub const Client = struct {
_ = c.close(fd);
return false;
}
- var cred: c.struct_ucred = undefined;
- var len: c.socklen_t = @sizeOf(@TypeOf(cred));
- if (c.getsockopt(fd, c.SOL_SOCKET, c.SO_PEERCRED, &cred, &len) != 0 or cred.uid != c.getuid()) {
+ const same_user = if (platform.peer.of(fd)) |peer| peer.uid == c.getuid() else false;
+ if (!same_user) {
_ = c.close(fd);
return false;
}
diff --git a/src/icon_service.zig b/src/icon_service.zig
index 6c4a233..4a1e983 100644
--- a/src/icon_service.zig
+++ b/src/icon_service.zig
@@ -21,6 +21,7 @@
// fd, down to "never call back into compositor code from the worker
// thread directly."
const std = @import("std");
+const platform = @import("platform");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const posix = std.posix;
@@ -122,8 +123,7 @@ pub const IconService = struct {
const self = try allocator.create(IconService);
errdefer allocator.destroy(self);
- const efd = c.eventfd(0, @intCast(std.os.linux.EFD.CLOEXEC | std.os.linux.EFD.NONBLOCK));
- if (efd < 0) return error.EventFdFailed;
+ const efd = platform.wake.create() orelse return error.EventFdFailed;
errdefer _ = c.close(efd);
self.* = .{ .allocator = allocator, .cfg = cfg, .io = io, .eventfd = efd };
diff --git a/src/ipc/server.zig b/src/ipc/server.zig
index 191dc7d..3a92bd5 100644
--- a/src/ipc/server.zig
+++ b/src/ipc/server.zig
@@ -321,12 +321,6 @@ pub fn onSequenceComplete(vi: *@import("../input/virtual.zig").VirtualInput, seq
client.updateFdInterest() catch {};
}
-const Ucred = extern struct {
- pid: std.posix.pid_t,
- uid: std.posix.uid_t,
- gid: std.posix.gid_t,
-};
-
pub fn parseFlatpakAppId(content: []const u8) ?[]const u8 {
var in_application_section = false;
var line_it = std.mem.splitScalar(u8, content, '\n');
@@ -409,26 +403,18 @@ fn handleListenerFd(fd: c_int, mask: wl.EventMask, ipc: *IpcServer) c_int {
);
if (client_fd < 0) return 0;
- var ucred: Ucred = undefined;
- var ucred_len: std.posix.socklen_t = @sizeOf(Ucred);
- if (c.getsockopt(
- client_fd,
- std.posix.SOL.SOCKET,
- std.posix.SO.PEERCRED,
- @ptrCast(&ucred),
- &ucred_len,
- ) < 0) {
+ const peer = platform.peer.of(client_fd) orelse {
closeFd(client_fd);
return 0;
- }
+ };
- if (ucred.uid != c.getuid()) {
- log.warn("rejecting IPC connection from UID {d} (expected {d})", .{ ucred.uid, c.getuid() });
+ if (peer.uid != c.getuid()) {
+ log.warn("rejecting IPC connection from UID {d} (expected {d})", .{ peer.uid, c.getuid() });
closeFd(client_fd);
return 0;
}
- const sandbox_opt = detectSandbox(ucred.pid, client_fd, ipc.allocator);
+ const sandbox_opt = detectSandbox(peer.pid, client_fd, ipc.allocator);
if (sandbox_opt) |sb| {
const groups = ipc.compositor.config.sandboxAllowGroups(sb.app_id, sb.engine);
if (!groups.contains(.ipc)) {
@@ -665,7 +651,7 @@ fn requirePrivateDir(dir: []const u8) IpcError!void {
var info: linux.Statx = undefined;
const rc = linux.statx(linux.AT.FDCWD, &buf, 0, .{ .UID = true, .MODE = true }, &info);
if (linux.errno(rc) != .SUCCESS) return error.NoRuntimeDir;
- if (info.uid != linux.getuid() or info.mode & 0o077 != 0) {
+ if (info.uid != c.getuid() or info.mode & 0o077 != 0) {
log.err("IPC socket directory {s} is not private to this uid", .{dir});
return error.RuntimeDirNotPrivate;
}
diff --git a/src/main.zig b/src/main.zig
index bb38373..1391d16 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -26,7 +26,7 @@ pub fn main(init: std.process.Init) void {
// Every client, helper and autostart item would inherit root. rediwm-dm
// and rediwm-session run the compositor as the logged-in user; seat
// access comes from logind, so root is never needed.
- if (std.os.linux.getuid() == 0 or std.os.linux.geteuid() == 0) {
+ if (std.c.getuid() == 0 or std.c.geteuid() == 0) {
log.err("refusing to run as root; start rediwm as a regular user", .{});
std.process.exit(1);
}
@@ -71,9 +71,9 @@ pub fn main(init: std.process.Init) void {
if (!restart) return;
// start's defers have released the seat and removed the IPC/Wayland sockets.
@import("session/activation.zig").setSessionFdInheritance(init.minimal.environ, true);
- const rc = std.os.linux.execve(executable.ptr, argv.ptr, init.minimal.environ.block.slice.ptr);
+ const rc = std.c.execve(executable.ptr, argv.ptr, init.minimal.environ.block.slice.ptr);
@import("session/activation.zig").setSessionFdInheritance(init.minimal.environ, false);
- log.err("restart execve failed ({t}); restoring the current compositor", .{std.os.linux.errno(rc)});
+ log.err("restart execve failed ({t}); restoring the current compositor", .{std.posix.errno(rc)});
}
}
diff --git a/src/pdf/print.c b/src/pdf/print.c
index de34b86..7f7860a 100644
--- a/src/pdf/print.c
+++ b/src/pdf/print.c
@@ -12,7 +12,7 @@
#include <signal.h>
#include <stdio.h>
#include <string.h>
-#include <sys/prctl.h>
+#include "../platform/process.h"
#include <sys/socket.h>
#include <unistd.h>
@@ -234,7 +234,7 @@ static int keep_only(int a, int b) {
static int run(int document, int peer, const char *path) {
// The viewer's other descriptors (Wayland, the caller's) are not ours.
if (keep_only(document, peer) < 0) return 1;
- prctl(PR_SET_NAME, "rediwm-pdf-prnt", 0, 0, 0);
+ rediwm_process_set_name("rediwm-pdf-prnt");
signal(SIGCHLD, SIG_DFL);
int devnull = open("/dev/null", O_RDONLY | O_CLOEXEC);
if (devnull >= 0) {
diff --git a/src/pdf/sandbox.c b/src/pdf/sandbox.c
index 7c6533d..aa9f48c 100644
--- a/src/pdf/sandbox.c
+++ b/src/pdf/sandbox.c
@@ -9,7 +9,7 @@
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
-#include <sys/prctl.h>
+#include "../platform/process.h"
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/syscall.h>
@@ -156,8 +156,8 @@ int rediwm_pdf_sandbox_enter(int document, int display, int print) {
if (single_threaded() < 0 || close_inherited(keep, kept) < 0) return -1;
struct rlimit core = {0, 0}, memory = {2ULL << 30, 2ULL << 30}, files = {128, 128};
if (setrlimit(RLIMIT_CORE, &core) < 0 || setrlimit(RLIMIT_AS, &memory) < 0 ||
- setrlimit(RLIMIT_NOFILE, &files) < 0 || prctl(PR_SET_DUMPABLE, 0) < 0 ||
- prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) return -1;
+ setrlimit(RLIMIT_NOFILE, &files) < 0 || rediwm_process_deny_dumps() < 0 ||
+ rediwm_process_no_new_privileges() < 0) return -1;
if (filesystem_policy() < 0) return -1;
return rediwm_pdf_syscall_policy(display);
}
diff --git a/src/platform/AGENTS.md b/src/platform/AGENTS.md
index b5b3037..5283e60 100644
--- a/src/platform/AGENTS.md
+++ b/src/platform/AGENTS.md
@@ -1,10 +1,12 @@
# Platform module
The one place the OS shows: child handles (`child.zig`), directory watching
-(`watch.zig`), the program's own path (`exe.zig`), where the system's helper
-programs live (`tool.zig`), seccomp-BPF filters
+(`watch.zig`), the program's own path (`exe.zig`), who is on the other end of a
+unix socket (`peer.zig`), process attributes such as no core dumps and no new
+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` for C and C++. Std only, no compositor imports. Linux
+`child.h`/`self_exe.h`/`peer.h`/`process.h` for C and C++. Std only, no compositor imports. Linux
today; the FreeBSD port (`docs/plans/freebsd.md`) adds `freebsd_*.zig` parts
without changing callers.
@@ -39,8 +41,17 @@ without changing callers.
directories. Everything else is looked up on `PATH` (`config.app_theme.executable`)
or spawned by bare name, which `std.process.spawn` resolves on the process's
`PATH`; never write `/usr/bin/<tool>`, ports live in `/usr/local`.
+* **`peer.of` names the socket's creator,** as of `connect` or `socketpair`; it
+ says nothing about who writes later (a forked child shares the descriptor).
+ `null` means refuse. `peer.h` needs `_GNU_SOURCE` (glibc hides `SO_PEERCRED`
+ without it) and, like `peer.zig`, refuses to build for another OS until the
+ port.
* Nothing here arms a timer or starts a thread; a caller retrying a failed
`add` owns that clock.
-Still direct Linux calls (later steps of the plan's phase P): `signalfd`/`epoll`
-in the supervisor and DM daemon, `kill`/`wait4`, `/proc` walks, `SO_PEERCRED`.
+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`), `statx` and `getdents64` in Files and the IPC socket check,
+`/proc` walks, and the terminal's per-message `SCM_CREDENTIALS` check
+(`files/terminal/engine.c`). Everything else outside this directory calls libc
+or `std.posix`.
diff --git a/src/platform/child.zig b/src/platform/child.zig
index 60725ae..8bc1022 100644
--- a/src/platform/child.zig
+++ b/src/platform/child.zig
@@ -6,8 +6,8 @@
const std = @import("std");
const linux = std.os.linux;
-pub const Pid = linux.pid_t;
-pub const Signal = linux.SIG;
+pub const Pid = std.posix.pid_t;
+pub const Signal = std.posix.SIG;
pub const Error = error{
/// The process is gone (or was never there).
@@ -129,6 +129,24 @@ pub fn signalGroup(pgid: Pid, sig: Signal) void {
_ = linux.kill(-pgid, sig);
}
+/// Kills a child nobody is going to wait for and collects it, so it leaves no
+/// zombie. Blocks until the kernel has taken it; SIGKILL cannot be caught.
+pub fn killAndReap(pid: Pid) void {
+ _ = linux.kill(pid, .KILL);
+ var status: u32 = 0;
+ while (linux.errno(linux.wait4(pid, @ptrCast(&status), 0, null)) == .INTR) {}
+}
+
+test "a child nobody watches is killed and collected" {
+ var child = try std.process.spawn(std.testing.io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ const pid = child.id.?;
+ killAndReap(pid);
+ child.id = null;
+ // Collected: no zombie, and no child left to wait for.
+ try std.testing.expect(!exists(pid));
+ try std.testing.expectEqual(@as(?u32, null), reap(pid));
+}
+
/// Handles for poll-based clients. One fd joins the application's normal
/// event loop and turns readable when any member exits; a long-lived child
/// requires no thread and causes no wakeups.
diff --git a/src/platform/mod.zig b/src/platform/mod.zig
index 8a19e16..4625ba8 100644
--- a/src/platform/mod.zig
+++ b/src/platform/mod.zig
@@ -1,10 +1,15 @@
//! 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 and syscall filters.
+//! the system's helper programs live, who is on the other end of a unix socket,
+//! 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 exe = @import("exe.zig");
+pub const peer = @import("peer.zig");
+pub const process = @import("process.zig");
+pub const wake = @import("wake.zig");
pub const power_supply = @import("power_supply.zig");
pub const charge_limit = @import("charge_limit.zig");
pub const watch = @import("watch.zig");
@@ -14,6 +19,9 @@ pub const tool = @import("tool.zig");
test {
_ = child;
_ = exe;
+ _ = peer;
+ _ = process;
+ _ = wake;
_ = tool;
_ = watch;
_ = @import("seccomp_tests.zig");
diff --git a/src/platform/peer.h b/src/platform/peer.h
new file mode 100644
index 0000000..51f4cee
--- /dev/null
+++ b/src/platform/peer.h
@@ -0,0 +1,31 @@
+/* Who is on the other end of a connected unix socket, for the C and C++ code
+ * that cannot import platform/peer.zig; the same contract as peer.of(). Linux
+ * reads SO_PEERCRED, which glibc declares only under _GNU_SOURCE (the C++
+ * compilers define it themselves). */
+#ifndef REDIWM_PEER_H
+#define REDIWM_PEER_H
+
+#ifndef __linux__
+#error "platform/peer.h is not ported to this OS yet (docs/plans/freebsd.md, P.9)"
+#endif
+#ifndef _GNU_SOURCE
+#error "platform/peer.h needs _GNU_SOURCE defined before any system header"
+#endif
+
+#include <sys/socket.h>
+#include <sys/types.h>
+
+/* The user and process id of whoever made the other end of the connected unix
+ * socket `fd`, as of connect(2) or socketpair(2). Either output may be NULL.
+ * Returns 0, or -1 when the kernel gives no answer: refuse the peer. */
+static inline int rediwm_peer_credentials(int fd, uid_t *uid, pid_t *pid) {
+ struct ucred cred;
+ socklen_t size = sizeof cred;
+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &size) != 0 || size != sizeof cred)
+ return -1;
+ if (uid) *uid = cred.uid;
+ if (pid) *pid = cred.pid;
+ return 0;
+}
+
+#endif
diff --git a/src/platform/peer.zig b/src/platform/peer.zig
new file mode 100644
index 0000000..3be376e
--- /dev/null
+++ b/src/platform/peer.zig
@@ -0,0 +1,61 @@
+//! Who is on the other end of a connected unix socket. Linux reads
+//! SO_PEERCRED. `peer.h` is the same contract for C and C++.
+//!
+//! The answer names whoever made the other end, as of `connect` or
+//! `socketpair`; it says nothing about who writes later (see `AGENTS.md`).
+const std = @import("std");
+const builtin = @import("builtin");
+const linux = std.os.linux;
+
+// std.os.linux issues Linux syscall numbers on any target, so a build for
+// another OS must fail here and not ask its kernel something else.
+comptime {
+ if (builtin.os.tag != .linux)
+ @compileError("platform.peer is not ported to this OS yet (docs/plans/freebsd.md, P.9)");
+}
+
+pub const Credentials = struct {
+ uid: std.posix.uid_t,
+ pid: std.posix.pid_t,
+};
+
+/// The kernel's `struct ucred`.
+const Ucred = extern struct {
+ pid: std.posix.pid_t,
+ uid: std.posix.uid_t,
+ gid: std.posix.gid_t,
+};
+
+/// The user and process id of whoever made the other end of the connected unix
+/// socket `fd`. Null when the kernel gives no answer (not a socket, not
+/// connected): callers refuse the peer.
+pub fn of(fd: std.posix.fd_t) ?Credentials {
+ var cred: Ucred = undefined;
+ var len: linux.socklen_t = @sizeOf(Ucred);
+ const rc = linux.getsockopt(fd, linux.SOL.SOCKET, linux.SO.PEERCRED, @ptrCast(&cred), &len);
+ if (linux.errno(rc) != .SUCCESS or len != @sizeOf(Ucred)) return null;
+ return .{ .uid = cred.uid, .pid = cred.pid };
+}
+
+test "both ends of a socketpair name this process" {
+ var fds: [2]std.posix.fd_t = undefined;
+ try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.socketpair(linux.AF.UNIX, linux.SOCK.STREAM | linux.SOCK.CLOEXEC, 0, &fds)));
+ defer for (fds) |fd| {
+ _ = linux.close(fd);
+ };
+ for (fds) |fd| {
+ const peer = of(fd).?;
+ try std.testing.expectEqual(linux.getuid(), peer.uid);
+ try std.testing.expectEqual(linux.getpid(), peer.pid);
+ }
+}
+
+test "a descriptor that is not a connected socket has no peer" {
+ try std.testing.expect(of(-1) == null);
+ var fds: [2]std.posix.fd_t = undefined;
+ try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&fds, .{ .CLOEXEC = true })));
+ defer for (fds) |fd| {
+ _ = linux.close(fd);
+ };
+ try std.testing.expect(of(fds[0]) == null);
+}
diff --git a/src/platform/process.h b/src/platform/process.h
new file mode 100644
index 0000000..dae7ec5
--- /dev/null
+++ b/src/platform/process.h
@@ -0,0 +1,29 @@
+/* Process attributes that differ between systems, for the C code that cannot
+ * import platform/process.zig; the same contract. Linux uses prctl. */
+#ifndef REDIWM_PROCESS_H
+#define REDIWM_PROCESS_H
+
+#ifndef __linux__
+#error "platform/process.h is not ported to this OS yet (docs/plans/freebsd.md, P.4)"
+#endif
+
+#include <sys/prctl.h>
+
+/* No core dump, and other processes of the same user cannot ptrace this one
+ * or read its memory. Returns 0, or -1. */
+static inline int rediwm_process_deny_dumps(void) {
+ return prctl(PR_SET_DUMPABLE, 0);
+}
+
+/* From now on exec cannot give this process, or anything it starts, more
+ * privilege (setuid, file capabilities). Irreversible. Returns 0, or -1. */
+static inline int rediwm_process_no_new_privileges(void) {
+ return prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+}
+
+/* The calling thread's name, as ps and top show it (15 characters). */
+static inline void rediwm_process_set_name(const char *name) {
+ (void)prctl(PR_SET_NAME, name, 0, 0, 0);
+}
+
+#endif
diff --git a/src/platform/process.zig b/src/platform/process.zig
new file mode 100644
index 0000000..e1988f7
--- /dev/null
+++ b/src/platform/process.zig
@@ -0,0 +1,71 @@
+//! Process attributes that differ between systems: dying with the parent, being
+//! dumped or traced, gaining privileges through exec, adopting orphans. Linux
+//! uses prctl. `process.h` is the same for C.
+const std = @import("std");
+const builtin = @import("builtin");
+const linux = std.os.linux;
+const child = @import("child.zig");
+
+// std.os.linux issues Linux syscall numbers on any target, so a build for
+// another OS must fail here and not ask its kernel something else.
+comptime {
+ if (builtin.os.tag != .linux)
+ @compileError("platform.process is not ported to this OS yet (docs/plans/freebsd.md, P.4)");
+}
+
+pub const Error = error{Failed};
+
+fn check(rc: usize) Error!void {
+ if (linux.errno(rc) != .SUCCESS) return error.Failed;
+}
+
+/// Delivers `sig` to this process when its parent dies. A failure leaves the
+/// process as it was, and no caller can do better, so it is not reported.
+pub fn dieWithParent(sig: child.Signal) void {
+ _ = linux.prctl(@intFromEnum(linux.PR.SET_PDEATHSIG), @intFromEnum(sig), 0, 0, 0);
+}
+
+/// Marks the process non-dumpable: no core dump, and other processes of the
+/// same user cannot ptrace it or read its memory (a password sits in it).
+pub fn denyDumps() Error!void {
+ try check(linux.prctl(@intFromEnum(linux.PR.SET_DUMPABLE), 0, 0, 0, 0));
+}
+
+/// From now on exec cannot give this process, or anything it starts, more
+/// privilege (setuid, file capabilities). Irreversible.
+pub fn noNewPrivileges() Error!void {
+ try check(linux.prctl(@intFromEnum(linux.PR.SET_NO_NEW_PRIVS), 1, 0, 0, 0));
+}
+
+/// Whether this process adopts the orphans of its descendants.
+pub fn childSubreaper() Error!bool {
+ var on: c_int = 0;
+ try check(linux.prctl(@intFromEnum(linux.PR.GET_CHILD_SUBREAPER), @intFromPtr(&on), 0, 0, 0));
+ return on != 0;
+}
+
+pub fn setChildSubreaper(on: bool) Error!void {
+ try check(linux.prctl(@intFromEnum(linux.PR.SET_CHILD_SUBREAPER), @intFromBool(on), 0, 0, 0));
+}
+
+test "the subreaper setting is read, changed and restored" {
+ const before = try childSubreaper();
+ try setChildSubreaper(!before);
+ try std.testing.expectEqual(!before, try childSubreaper());
+ try setChildSubreaper(before);
+ try std.testing.expectEqual(before, try childSubreaper());
+}
+
+test "dumps are denied and the death signal is set, then both restored" {
+ const dumpable = linux.prctl(@intFromEnum(linux.PR.GET_DUMPABLE), 0, 0, 0, 0);
+ try std.testing.expect(linux.errno(dumpable) == .SUCCESS);
+ try denyDumps();
+ try std.testing.expectEqual(@as(usize, 0), linux.prctl(@intFromEnum(linux.PR.GET_DUMPABLE), 0, 0, 0, 0));
+ _ = linux.prctl(@intFromEnum(linux.PR.SET_DUMPABLE), dumpable, 0, 0, 0);
+
+ var signal: c_int = -1;
+ dieWithParent(.TERM);
+ _ = linux.prctl(@intFromEnum(linux.PR.GET_PDEATHSIG), @intFromPtr(&signal), 0, 0, 0);
+ try std.testing.expectEqual(@as(c_int, @intFromEnum(child.Signal.TERM)), signal);
+ _ = linux.prctl(@intFromEnum(linux.PR.SET_PDEATHSIG), 0, 0, 0, 0);
+}
diff --git a/src/platform/wake.zig b/src/platform/wake.zig
new file mode 100644
index 0000000..f0d08df
--- /dev/null
+++ b/src/platform/wake.zig
@@ -0,0 +1,39 @@
+//! Descriptors that wake a poll loop from another thread. Linux uses eventfd:
+//! writing 8 bytes (a u64 count) makes the descriptor readable, reading 8 bytes
+//! drains it.
+const std = @import("std");
+const builtin = @import("builtin");
+const linux = std.os.linux;
+
+// std.os.linux issues Linux syscall numbers on any target, so a build for
+// another OS must fail here and not ask its kernel something else.
+comptime {
+ if (builtin.os.tag != .linux)
+ @compileError("platform.wake is not ported to this OS yet (docs/plans/freebsd.md, P.4)");
+}
+
+/// A new wake descriptor: close-on-exec, non-blocking, count zero. The caller
+/// closes it. Null when the system refuses.
+pub fn create() ?std.posix.fd_t {
+ const rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
+ if (linux.errno(rc) != .SUCCESS) return null;
+ return @intCast(rc);
+}
+
+fn readable(fd: std.posix.fd_t) bool {
+ var fds = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.IN, .revents = 0 }};
+ return linux.errno(linux.poll(&fds, 1, 0)) == .SUCCESS and fds[0].revents != 0;
+}
+
+test "a wake descriptor turns readable when written and drains when read" {
+ const fd = create().?;
+ defer _ = linux.close(fd);
+ try std.testing.expect(!readable(fd));
+ const one: u64 = 1;
+ try std.testing.expectEqual(@as(usize, 8), linux.write(fd, std.mem.asBytes(&one), 8));
+ try std.testing.expect(readable(fd));
+ var count: u64 = 0;
+ try std.testing.expectEqual(@as(usize, 8), linux.read(fd, std.mem.asBytes(&count), 8));
+ try std.testing.expectEqual(@as(u64, 1), count);
+ try std.testing.expect(!readable(fd));
+}
diff --git a/src/polkit/helper.zig b/src/polkit/helper.zig
index 2bb6907..f4166d1 100644
--- a/src/polkit/helper.zig
+++ b/src/polkit/helper.zig
@@ -1,6 +1,7 @@
//! Nonblocking polkit helper transport. Callbacks borrow text until return and
//! may respond/cancel, but must not destroy this object or dispatch the loop.
const std = @import("std");
+const platform = @import("platform");
const wl = @import("wayland").server.wl;
const c = @import("c");
const Child = @import("../session/child.zig");
@@ -77,9 +78,7 @@ pub const Helper = struct {
self.fd = rediwm_polkit_spawn(&user, &pid);
if (self.fd < 0) return error.HelperUnavailable;
self.child = Child.watch(allocator, loop, pid, self, childExited) catch |err| {
- _ = std.os.linux.kill(pid, .KILL);
- var status: u32 = 0;
- while (std.os.linux.errno(std.os.linux.wait4(pid, @ptrCast(&status), 0, null)) == .INTR) {}
+ platform.child.killAndReap(pid);
return err;
};
spawned = true;
diff --git a/src/printing/http.zig b/src/printing/http.zig
index fc3dfcd..0e9e4d4 100644
--- a/src/printing/http.zig
+++ b/src/printing/http.zig
@@ -273,11 +273,11 @@ fn connectTcp(io: ?std.Io, target: endpoint.Endpoint, cancel: c_int, deadline: i
if (fd < 0) continue;
const result = switch (address) {
.ip4 => |ip| blk: {
- var addr: std.os.linux.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, ip.port), .addr = @bitCast(ip.bytes) };
+ var addr: std.posix.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, ip.port), .addr = @bitCast(ip.bytes) };
break :blk c.connect(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @sizeOf(@TypeOf(addr)));
},
.ip6 => |ip| blk: {
- var addr: std.os.linux.sockaddr.in6 = .{ .port = std.mem.nativeToBig(u16, ip.port), .flowinfo = ip.flow, .addr = ip.bytes, .scope_id = ip.interface.index };
+ var addr: std.posix.sockaddr.in6 = .{ .port = std.mem.nativeToBig(u16, ip.port), .flowinfo = ip.flow, .addr = ip.bytes, .scope_id = ip.interface.index };
break :blk c.connect(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @sizeOf(@TypeOf(addr)));
},
};
@@ -355,7 +355,7 @@ test "remote loopback HTTP preserves authority, resource and body" {
const listener = c.socket(c.AF_INET, c.SOCK_STREAM | c.SOCK_CLOEXEC, 0);
try t.expect(listener >= 0);
defer _ = c.close(listener);
- var address: std.os.linux.sockaddr.in = .{ .port = 0, .addr = @bitCast([4]u8{ 127, 0, 0, 1 }) };
+ var address: std.posix.sockaddr.in = .{ .port = 0, .addr = @bitCast([4]u8{ 127, 0, 0, 1 }) };
try t.expectEqual(@as(c_int, 0), c.bind(listener, .{ .__sockaddr__ = @ptrCast(&address) }, @sizeOf(@TypeOf(address))));
try t.expectEqual(@as(c_int, 0), c.listen(listener, 1));
var length: c.socklen_t = @sizeOf(@TypeOf(address));
diff --git a/src/printing/notifier.zig b/src/printing/notifier.zig
index a547a52..bfb55f5 100644
--- a/src/printing/notifier.zig
+++ b/src/printing/notifier.zig
@@ -36,7 +36,7 @@ pub const Listener = struct {
// must never introduce an unbounded resolver wait on the compositor.
const passwd = std.Io.Dir.cwd().readFileAlloc(io, "/etc/passwd", allocator, .limited(256 * 1024)) catch "";
defer if (passwd.len != 0) allocator.free(passwd);
- self.uids = serviceUids(passwd, @intCast(std.os.linux.getuid()));
+ self.uids = serviceUids(passwd, @intCast(std.c.getuid()));
_ = try conn.hello(self, onHello);
return self;
}
diff --git a/src/screenshot/worker.zig b/src/screenshot/worker.zig
index 6244f16..e78384e 100644
--- a/src/screenshot/worker.zig
+++ b/src/screenshot/worker.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const platform = @import("platform");
const posix = std.posix;
const c = std.posix.system;
const wl = @import("wayland").server.wl;
@@ -67,9 +68,7 @@ pub const WorkerPool = struct {
const pool = try allocator.create(WorkerPool);
errdefer allocator.destroy(pool);
- const efd_res = c.eventfd(0, @intCast(std.os.linux.EFD.CLOEXEC | std.os.linux.EFD.NONBLOCK));
- if (efd_res < 0) return error.EventFdFailed;
- const efd: posix.fd_t = efd_res;
+ const efd: posix.fd_t = platform.wake.create() orelse return error.EventFdFailed;
errdefer _ = c.close(efd);
pool.* = .{
diff --git a/src/server/wakeups.zig b/src/server/wakeups.zig
index aee2bd6..677810e 100644
--- a/src/server/wakeups.zig
+++ b/src/server/wakeups.zig
@@ -1,6 +1,7 @@
//! Server wake handlers: audio, battery and the GPU timer.
const std = @import("std");
+const platform = @import("platform");
const i18n = @import("i18n");
const Server = @import("../Server.zig");
const wl = @import("wayland").server.wl;
@@ -13,9 +14,7 @@ const gpu_timer_sched_keep_ns = 10 * std.time.ns_per_s;
/// UI catches up to an external volume change (another app, `pactl`) on its
/// next incidental repaint instead of immediately — never fatal.
pub fn createAudioWakeFd() ?std.posix.fd_t {
- const rc = std.os.linux.eventfd(0, std.os.linux.EFD.NONBLOCK | std.os.linux.EFD.CLOEXEC);
- if (std.os.linux.errno(rc) != .SUCCESS) return null;
- return @intCast(rc);
+ return platform.wake.create();
}
/// Runs on the compositor thread, woken by `audio.AudioManager`'s PA-thread
diff --git a/src/session/auth.c b/src/session/auth.c
index 4dea223..7534790 100644
--- a/src/session/auth.c
+++ b/src/session/auth.c
@@ -7,7 +7,7 @@
#include <string.h>
#include <sys/eventfd.h>
#include <sys/mman.h>
-#include <sys/prctl.h>
+#include "../platform/process.h"
#include <unistd.h>
#include <pwd.h>
@@ -100,7 +100,7 @@ struct rediwm_auth *rediwm_auth_start(const char *password) {
return NULL;
}
(void)mlock(auth, sizeof *auth);
- (void)prctl(PR_SET_DUMPABLE, 0);
+ (void)rediwm_process_deny_dumps();
strcpy(auth->password, password);
atomic_init(&auth->result, 0);
if (pthread_create(&auth->thread, NULL, authenticate, auth)) {
diff --git a/src/session/child.zig b/src/session/child.zig
index 60f86f0..e79b14b 100644
--- a/src/session/child.zig
+++ b/src/session/child.zig
@@ -110,7 +110,7 @@ test "an observed child is reported without being reaped, and a cancelled watch
// The exit was observed, not collected: the real owner still gets the status.
try std.testing.expectEqual(@as(?u32, null), seen.status);
const status = platform.child.reap(quick_pid).?;
- try std.testing.expectEqual(@as(u8, 5), std.os.linux.W.EXITSTATUS(status));
+ try std.testing.expectEqual(@as(u8, 5), std.posix.W.EXITSTATUS(status));
quick.id = null;
var slow = try std.process.spawn(std.testing.io, .{ .argv = &.{ "/bin/sleep", "30" } });
diff --git a/src/session/greeter.zig b/src/session/greeter.zig
index e9d555d..44736f1 100644
--- a/src/session/greeter.zig
+++ b/src/session/greeter.zig
@@ -77,7 +77,7 @@ pub const Greeter = struct {
if (environ.getPosix("REDIWM_GREETER_FD")) |fd_str| {
if (std.fmt.parseInt(c_int, fd_str, 10)) |fd| {
// Nothing the greeter might spawn inherits the daemon socket.
- _ = std.os.linux.fcntl(fd, std.os.linux.F.SETFD, std.os.linux.FD_CLOEXEC);
+ _ = c.fcntl(fd, c.F_SETFD, c.FD_CLOEXEC);
self.client = dm_ipc.Client.fromFd(fd);
self.watch() catch {
self.client.?.close();
diff --git a/src/session/lock.zig b/src/session/lock.zig
index 0aa25e5..d9ae92c 100644
--- a/src/session/lock.zig
+++ b/src/session/lock.zig
@@ -5,6 +5,7 @@
//! picks an account and session and signs in through rediwm-dm, then exits.
const i18n = @import("i18n");
const std = @import("std");
+const platform = @import("platform");
const Child = @import("child.zig");
const wl = @import("wayland").server.wl;
const wlr = @import("wlroots");
@@ -132,7 +133,7 @@ pub const Lock = struct {
// First, so a crash anywhere below still restarts the session locked.
announce(server, true);
_ = c.mlock(&self.password, self.password.len);
- _ = c.prctl(c.PR_SET_DUMPABLE, @as(c_ulong, 0), @as(c_ulong, 0), @as(c_ulong, 0), @as(c_ulong, 0));
+ platform.process.denyDumps() catch {};
server.switcher.cancel();
server.screenshot_selector.cancel();
server.locker = self;
diff --git a/src/session/services.zig b/src/session/services.zig
index e57aecd..0151960 100644
--- a/src/session/services.zig
+++ b/src/session/services.zig
@@ -6,6 +6,7 @@
//! Does not touch unrelated user services or the systemd user manager.
const std = @import("std");
+const platform = @import("platform");
const wl = @import("wayland").server.wl;
const Child = @import("child.zig");
@@ -65,9 +66,7 @@ pub const Manager = struct {
.loop = server.wl_server.getEventLoop(),
};
- const efd_rc = std.os.linux.eventfd(0, std.os.linux.EFD.NONBLOCK | std.os.linux.EFD.CLOEXEC);
- if (std.os.linux.errno(efd_rc) != .SUCCESS) return error.EventFdFailed;
- const signal_fd: std.posix.fd_t = @intCast(efd_rc);
+ const signal_fd: std.posix.fd_t = platform.wake.create() orelse return error.EventFdFailed;
mgr.signal_fd = signal_fd;
global_signal_fd.store(signal_fd, .release);
@@ -268,7 +267,7 @@ test "session helper tracking and bounded shutdown" {
child.id = null; // ownership was transferred to the watcher
try mgr.loop.dispatch(1000);
var status: u32 = 0;
- try std.testing.expectEqual(std.os.linux.E.CHILD, std.os.linux.errno(std.os.linux.wait4(pid, @ptrCast(&status), std.os.linux.W.NOHANG, null)));
+ try std.testing.expectEqual(std.posix.E.CHILD, std.posix.errno(std.c.wait4(pid, @ptrCast(&status), std.posix.W.NOHANG, null)));
// Immediate exits are readable even if they occur before registration.
var quick = try std.process.spawn(std.testing.io, .{ .argv = &.{ "/bin/sh", "-c", "exit 7" } });
@@ -278,5 +277,5 @@ test "session helper tracking and bounded shutdown" {
quick.id = null;
try mgr.loop.dispatch(1000);
try std.testing.expectEqual(@as(usize, 0), mgr.countTracked());
- try std.testing.expectEqual(std.os.linux.E.CHILD, std.os.linux.errno(std.os.linux.wait4(quick_pid, @ptrCast(&status), std.os.linux.W.NOHANG, null)));
+ try std.testing.expectEqual(std.posix.E.CHILD, std.posix.errno(std.c.wait4(quick_pid, @ptrCast(&status), std.posix.W.NOHANG, null)));
}
diff --git a/src/session/supervisor.zig b/src/session/supervisor.zig
index fd96299..a5b83ac 100644
--- a/src/session/supervisor.zig
+++ b/src/session/supervisor.zig
@@ -42,10 +42,9 @@ pub fn Options(comptime Publication: type) type {
pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8 {
const allocator = options.allocator;
- var previous_subreaper: c_int = 0;
- _ = try sys.check(linux.prctl(@intFromEnum(linux.PR.GET_CHILD_SUBREAPER), @intFromPtr(&previous_subreaper), 0, 0, 0));
- _ = try sys.check(linux.prctl(@intFromEnum(linux.PR.SET_CHILD_SUBREAPER), 1, 0, 0, 0));
- defer _ = linux.prctl(@intFromEnum(linux.PR.SET_CHILD_SUBREAPER), @intCast(previous_subreaper), 0, 0, 0);
+ const previous_subreaper = try platform.process.childSubreaper();
+ try platform.process.setChildSubreaper(true);
+ defer platform.process.setChildSubreaper(previous_subreaper) catch {};
var preexisting = try descendants(allocator, linux.getpid());
defer preexisting.deinit(allocator);
diff --git a/src/session_restart.zig b/src/session_restart.zig
index 7f56ac2..3b2cceb 100644
--- a/src/session_restart.zig
+++ b/src/session_restart.zig
@@ -11,14 +11,13 @@
const std = @import("std");
const linux = std.os.linux;
const c = std.posix.system;
+const platform = @import("platform");
const default_installed = @import("install_paths").bin ++ "/rediwm";
const io_timeout_s = 3;
const ready_timeout_ms = 20_000;
const poll_interval_ms = 200;
-const Ucred = extern struct { pid: i32, uid: u32, gid: u32 };
-
const Session = struct {
path: []const u8,
fd: c_int,
@@ -141,16 +140,15 @@ fn connect(arena: std.mem.Allocator, path: []const u8, installed: []const u8) ?S
return null;
}
- var cred: Ucred = undefined;
- var cred_len: std.posix.socklen_t = @sizeOf(Ucred);
- if (c.getsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.PEERCRED, @ptrCast(&cred), &cred_len) < 0 or
- cred.uid != c.getuid() or
- !runsInstalled(arena, cred.pid, installed))
- {
+ const peer = platform.peer.of(fd) orelse {
+ closeFd(fd);
+ return null;
+ };
+ if (peer.uid != c.getuid() or !runsInstalled(arena, peer.pid, installed)) {
closeFd(fd);
return null;
}
- return .{ .path = path, .fd = fd, .pid = cred.pid };
+ return .{ .path = path, .fd = fd, .pid = peer.pid };
}
fn runsInstalled(arena: std.mem.Allocator, pid: i32, installed: []const u8) bool {
diff --git a/src/start_menu/applications.zig b/src/start_menu/applications.zig
index 36e7cf1..42ddeea 100644
--- a/src/start_menu/applications.zig
+++ b/src/start_menu/applications.zig
@@ -122,8 +122,7 @@ pub const Catalog = struct {
errdefer loading.release();
loading.loading = scan;
- const efd = c.eventfd(0, @intCast(std.os.linux.EFD.CLOEXEC | std.os.linux.EFD.NONBLOCK));
- if (efd < 0) return error.EventFdFailed;
+ const efd = platform.wake.create() orelse return error.EventFdFailed;
errdefer _ = c.close(efd);
const owned_locale = try allocator.dupe(u8, locale_tag);
diff --git a/src/start_menu/catalog_cache.zig b/src/start_menu/catalog_cache.zig
index f2ecf09..b09d722 100644
--- a/src/start_menu/catalog_cache.zig
+++ b/src/start_menu/catalog_cache.zig
@@ -159,7 +159,7 @@ pub fn write(allocator: Allocator, io: Io, environ: std.process.Environ, payload
return;
}
- const tmp = std.fmt.allocPrint(arena, "{s}.tmp-{d}", .{ path, std.os.linux.getpid() }) catch return;
+ const tmp = std.fmt.allocPrint(arena, "{s}.tmp-{d}", .{ path, std.c.getpid() }) catch return;
Io.Dir.cwd().writeFile(io, .{ .sub_path = tmp, .data = encoded }) catch |err| {
log.warn("catalog cache write {s}: {}", .{ tmp, err });
return;
diff --git a/src/theme_helper/native.c b/src/theme_helper/native.c
index b3732c1..4bcfd6a 100644
--- a/src/theme_helper/native.c
+++ b/src/theme_helper/native.c
@@ -15,7 +15,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <sys/prctl.h>
+#include "../platform/process.h"
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
@@ -348,7 +348,7 @@ int rediwm_theme_copy(const char *src,const char *dst) {total=0;return copy_file
static int parser_sandbox(const char *root, const char *source, int writable) {
struct rlimit memory={512u*1024u*1024u,512u*1024u*1024u};
if(setrlimit(RLIMIT_AS,&memory)<0)return -1;
- if(prctl(PR_SET_NO_NEW_PRIVS,1,0,0,0)<0)return -1;
+ if(rediwm_process_no_new_privileges()<0)return -1;
#ifdef SYS_landlock_create_ruleset
int abi=syscall(SYS_landlock_create_ruleset,NULL,0,LANDLOCK_CREATE_RULESET_VERSION);
if(abi>0) {
diff --git a/src/toplevel/focus_close.zig b/src/toplevel/focus_close.zig
index b641649..1f17922 100644
--- a/src/toplevel/focus_close.zig
+++ b/src/toplevel/focus_close.zig
@@ -92,13 +92,13 @@ pub fn forceClose(toplevel: *Toplevel) void {
.xdg => {
const client = toplevel.waylandClient() orelse return;
const pid = client.getCredentials().pid;
- if (pid > 1 and pid != std.os.linux.getpid()) std.posix.kill(pid, std.posix.SIG.KILL) catch {};
+ if (pid > 1 and pid != std.c.getpid()) std.posix.kill(pid, std.posix.SIG.KILL) catch {};
client.destroy();
},
.xwayland => |*adapter| if (toplevel.server.xwayland) |xwayland| xwayland.forceClose(adapter.xsurface.window_id),
.placeholder => |*ph| {
if (ph.pid) |pid| {
- if (pid > 1 and pid != std.os.linux.getpid()) std.posix.kill(pid, std.posix.SIG.KILL) catch {};
+ if (pid > 1 and pid != std.c.getpid()) std.posix.kill(pid, std.posix.SIG.KILL) catch {};
}
ph.cancel(toplevel);
},
diff --git a/src/trash_drop.zig b/src/trash_drop.zig
index a26a27a..86388c1 100644
--- a/src/trash_drop.zig
+++ b/src/trash_drop.zig
@@ -10,6 +10,7 @@
//! moving, as Files and the desktop do. The drag is finished when `gio` exits,
//! so the source learns whether it worked.
const std = @import("std");
+const platform = @import("platform");
const wl = @import("wayland").server.wl;
const wlr = @import("wlroots");
const i18n = @import("i18n");
@@ -170,9 +171,7 @@ fn trash(self: *Self, a: std.mem.Allocator, paths: []const []const u8) void {
app_scope.place(server, pid, "gio");
self.child = Child.watch(gpa, server.wl_server.getEventLoop(), pid, self, exited) catch {
// Nobody would collect it.
- _ = std.os.linux.kill(pid, .KILL);
- var status: u32 = 0;
- while (std.os.linux.errno(std.os.linux.wait4(pid, @ptrCast(&status), 0, null)) == .INTR) {}
+ platform.child.killAndReap(pid);
return self.failed();
};
}
@@ -180,7 +179,7 @@ fn trash(self: *Self, a: std.mem.Allocator, paths: []const []const u8) void {
fn exited(owner: ?*anyopaque, _: *Child, status: ?u32) void {
const self: *Self = @ptrCast(@alignCast(owner.?));
self.child = null;
- const ok = if (status) |value| std.os.linux.W.IFEXITED(value) and std.os.linux.W.EXITSTATUS(value) == 0 else false;
+ const ok = if (status) |value| std.posix.W.IFEXITED(value) and std.posix.W.EXITSTATUS(value) == 0 else false;
if (ok) self.target.finish(true) else self.failed();
}
diff --git a/src/wallpaper_load.zig b/src/wallpaper_load.zig
index b1f4482..d7b8f93 100644
--- a/src/wallpaper_load.zig
+++ b/src/wallpaper_load.zig
@@ -3,6 +3,7 @@
// Appearance page's preview) that the compositor thread wraps in ImageBuffer
// after the eventfd wake.
const std = @import("std");
+const platform = @import("platform");
const Allocator = std.mem.Allocator;
const posix = std.posix;
const c = std.posix.system;
@@ -67,8 +68,7 @@ pub const Loader = struct {
owned += 1;
}
- const efd = c.eventfd(0, @intCast(std.os.linux.EFD.CLOEXEC | std.os.linux.EFD.NONBLOCK));
- if (efd < 0) return error.EventFdFailed;
+ const efd = platform.wake.create() orelse return error.EventFdFailed;
errdefer _ = c.close(efd);
self.* = .{
diff --git a/src/wallpaper_strip.zig b/src/wallpaper_strip.zig
index bebbaf9..a115da3 100644
--- a/src/wallpaper_strip.zig
+++ b/src/wallpaper_strip.zig
@@ -3,6 +3,7 @@
// finished ones after the eventfd wake. Like wallpaper_load.zig, the worker
// never touches wlroots or GPU objects.
const std = @import("std");
+const platform = @import("platform");
const Allocator = std.mem.Allocator;
const posix = std.posix;
const c = std.posix.system;
@@ -45,8 +46,7 @@ pub const Strip = struct {
const thumbs = try allocator.alloc(?[]u32, entries.len);
errdefer allocator.free(thumbs);
@memset(thumbs, null);
- const efd = c.eventfd(0, @intCast(std.os.linux.EFD.CLOEXEC | std.os.linux.EFD.NONBLOCK));
- if (efd < 0) return error.EventFdFailed;
+ const efd = platform.wake.create() orelse return error.EventFdFailed;
errdefer _ = c.close(efd);
self.* = .{ .allocator = allocator, .io = io, .paths = paths, .thumbs = thumbs, .eventfd = efd };
self.thread = try std.Thread.spawn(.{}, run, .{self});
diff --git a/tests/files_transfers_ui.py b/tests/files_transfers_ui.py
deleted file mode 100644
index 92b53bb..0000000
--- a/tests/files_transfers_ui.py
+++ /dev/null
@@ -1,169 +0,0 @@
-#!/usr/bin/env python3
-"""Files add flow and background tray, on a private headless desktop."""
-import hashlib
-import os
-from pathlib import Path
-import subprocess
-import sys
-import tempfile
-import time
-import libtorrent as lt
-from files_torrents import Client, wait, ROOT
-from ipc_client import IPCClient, spawn_compositor, stop_process
-
-def run():
- with tempfile.TemporaryDirectory(prefix='rediwm-transfer-ui-') as directory:
- tmp = Path(directory)
- home = tmp/'Home'; home.mkdir()
- torrent = tmp/'example.torrent'
- torrent.write_bytes(lt.bencode({'info': {'name': 'example.txt', 'length': 5, 'piece length': 16384, 'pieces': hashlib.sha1(b'hello').digest()}}))
- shim = tmp/'network.so'
- subprocess.run(['cc','-shared','-fPIC',str(ROOT/'tests/torrent_network.c'),'-o',str(shim),'-ldl'],check=True)
- env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), XDG_STATE_HOME=str(tmp/'state'),
- XDG_DATA_HOME=str(tmp/'data'), XDG_CONFIG_HOME=str(tmp/'config'), HOME=str(home),
- GIO_USE_VFS='local', REDIWM_FILES_DEVICES='0', REDIWM_APP_SCOPES='0', LD_PRELOAD=str(shim),
- DBUS_SYSTEM_BUS_ADDRESS='unix:path=/nonexistent-rediwm-test-bus')
- for key in ('REDIWM_SOCKET', 'WAYLAND_DISPLAY', 'DISPLAY'):
- env.pop(key, None)
- binary_dir = Path(os.environ.get('REDIWM_TEST_BIN_DIR', ROOT/'zig-out/bin'))
- proc, log = spawn_compositor(tmp, binary=binary_dir/'rediwm', env_extra=dict({k:v for k,v in env.items() if k != "LD_PRELOAD"}, REDIWM_FORCE_DBUS='1', WLR_RENDERER_ALLOW_SOFTWARE='1',
- PULSE_SERVER='unix:/nonexistent-rediwm-test-audio'))
- files = None; client = None
- try:
- # This socket pattern deliberately excludes the transfer service.
- ipc_path = wait(lambda: next(iter(tmp.glob('rediwm-*.sock')),None),'compositor socket')
- with IPCClient(ipc_path) as ipc:
- ipc.wait_for('wallpaper_presented',timeout_ms=10000)
- display = wait(lambda: next((p.name for p in tmp.glob('wayland-*') if not p.name.endswith('.lock')),None),'Wayland')
- env['WAYLAND_DISPLAY'] = display
- files = subprocess.Popen([str(binary_dir/'rediwm-files'),'--torrent',str(torrent)],env=env,stdout=log,stderr=log)
- def windows(): return [w for w in ipc.get_windows() if w['app_id']=='rediwm-files']
- win = wait(lambda: next(iter(windows()),None),'Files window')
- ipc.focus_window(win['id']); ipc.wait_for('window_geometry_settled',window_id=win['id'])
- wait(lambda: (tmp/'files-transfers.sock').exists(),'helper socket')
- client = Client(tmp)
- time.sleep(.3)
- ipc.key_down_up(28) # Confirm the displayed destination folder.
- rows = client.until(lambda r: r if r else None,'UI adds torrent')
- assert rows[0]['pending'] and rows[0]['metadata']
- rect = ipc.get_window_debug(win['id'])['client_box']
- width,height = rect['width'],rect['height']
- bx=(width-min(720,width-24))/2; by=(height-min(560,height-24))/2
- def pane_click(x,y): ipc.click_at(round(rect['x']+x),round(rect['y']+y)); time.sleep(.15)
- def click(x,y): pane_click(bx+x,by+y)
- def title(): return next(w['title'] for w in windows() if w['id'] == win['id'])
- wait(lambda: title().startswith('Transfers —'),'Transfers uses the main pane')
- Path('/tmp/rediwm-transfers-list.png').unlink(missing_ok=True)
- ipc.screenshot(path='/tmp/rediwm-transfers-list.png',window_id=win['id'])
- pane_click(60,82) # Add torrent is in the ordinary Files toolbar.
- ipc.key_down_up(1) # Cancel returns to the list.
- assert title().startswith('Transfers —')
- pane_click(283,180) # first list row opens its file selection
- Path('/tmp/rediwm-transfers-files.png').unlink(missing_ok=True)
- ipc.screenshot(path='/tmp/rediwm-transfers-files.png',window_id=win['id'])
- click(min(720,width-24)-75,min(560,height-24)-42) # Start download
- client.until(lambda r: r and not r[0]['pending'] and not r[0]['paused'],'UI starts torrent')
- ipc.key_down_up(1) # Close details, leaving the transfer list visible.
- pane_click(290,82) # Stop seeding must preserve an active download.
- client.until(lambda r: r and not r[0]['paused'],'Stop seeding preserves downloads')
- pane_click(180,82) # Pause all in the main toolbar.
- client.until(lambda r: r and r[0]['paused'],'toolbar Pause all')
- pane_click(283,180)
- click(76,164) # Resume from transfer details.
- client.until(lambda r: r and not r[0]['paused'],'resume after toolbar pause')
- ipc.key_down_up(1)
- ipc.action('set_window_size', {'id': win['id'], 'width': 360, 'height': 540})
- ipc.wait_for('window_geometry_settled',window_id=win['id'])
- rect = ipc.get_window_debug(win['id'])['client_box']
- pane_click(170,128) # Narrow windows wrap the torrent actions below the view icons.
- client.until(lambda r: r and r[0]['paused'],'narrow toolbar Pause all')
- Path('/tmp/rediwm-transfers-narrow.png').unlink(missing_ok=True)
- ipc.screenshot(path='/tmp/rediwm-transfers-narrow.png',window_id=win['id'])
- client.send(op='resume',id=rows[0]['id'])
- client.until(lambda r: r and not r[0]['paused'],'resume after narrow toolbar pause')
- ipc.action('set_window_size', {'id': win['id'], 'width': width, 'height': height})
- ipc.wait_for('window_geometry_settled',window_id=win['id'])
- rect = ipc.get_window_debug(win['id'])['client_box']
- pane_click(27,28) # Back returns to the previous folder.
- wait(lambda: not title().startswith('Transfers —'),'Back leaves Transfers')
- # Grid cards have the same inline controls on their detail line.
- pane_click(425,227)
- client.until(lambda r: r and r[0]['paused'],'grid card Pause')
- pane_click(425,227)
- client.until(lambda r: r and not r[0]['paused'],'grid card Resume')
- # Download controls are also available in the destination folder.
- pane_click(width-233,82) # ordinary Files list view
- time.sleep(.3)
- name_right = 228 + (width-208-40-14)*.5 - 4
- toggle_x, ring_x = name_right-14, name_right-46
- pane_click(toggle_x,180)
- client.until(lambda r: r and r[0]['paused'],'folder row Pause')
- pane_click(toggle_x,180)
- client.until(lambda r: r and not r[0]['paused'],'folder row Resume')
- ipc.action('move_cursor', {'x': round(rect['x']+ring_x), 'y': round(rect['y']+180)})
- time.sleep(.2)
- Path('/tmp/rediwm-transfers-folder.png').unlink(missing_ok=True)
- ipc.screenshot(path='/tmp/rediwm-transfers-folder.png',window_id=win['id'])
- # Keyboard activation on a staging entry opens transfer details.
- pane_click(280,180)
- ipc.key_down_up(57)
- client.until(lambda r: r and r[0]['paused'],'keyboard row Pause')
- ipc.key_down_up(57)
- client.until(lambda r: r and not r[0]['paused'],'keyboard row Resume')
- ipc.key_down_up(28)
- ipc.key_down_up(1)
- # The actual .torrent file has the same controls, independent of its destination.
- ipc.key(29,True); ipc.key_down_up(38); ipc.key(29,False)
- ipc.type_text(str(tmp)); ipc.key_down_up(28)
- wait(lambda: title().startswith(tmp.name+' —'),'source folder')
- ipc.key(29,True); ipc.key_down_up(33); ipc.key(29,False)
- ipc.type_text('example.torrent'); time.sleep(.3)
- pane_click(toggle_x,180)
- client.until(lambda r: r and r[0]['paused'],'source .torrent row Pause')
- pane_click(toggle_x,180)
- client.until(lambda r: r and not r[0]['paused'],'source .torrent row Resume')
- ipc.key(29,True); ipc.key_down_up(38); ipc.key(29,False)
- ipc.type_text(str(home)); ipc.key_down_up(28)
- wait(lambda: title().startswith('Home —'),'return to download folder')
- # The sidebar remains usable while viewing Transfers.
- # Ten places and a 40px block gap precede Transfers at this height.
- pane_click(80,532)
- wait(lambda: title().startswith('Transfers —'),'sidebar reopens Transfers')
- Path('/tmp/rediwm-transfers-list.png').unlink(missing_ok=True)
- ipc.screenshot(path='/tmp/rediwm-transfers-list.png',window_id=win['id'])
- def icons(): return ipc.get_shell_state()['taskbars'][0]['app_tray']
- wait(lambda: len(icons())==1,'active transfer tray icon')
- ipc.close_window(win['id']); files.wait(timeout=8)
- client.until(lambda r: r and not r[0]['paused'],'transfer survives Files closing')
- icon=icons()[0]['box']
- ipc.click_at(icon['x']+icon['width']//2,icon['y']+icon['height']//2)
- reopened = wait(lambda: next(iter(windows()),None),'tray reopens Files')
- ipc.wait_for('window_geometry_settled',window_id=reopened['id'])
- icon=icons()[0]['box']
- ipc.click_at(icon['x']+icon['width']//2,icon['y']+icon['height']//2,0x111)
- menu=wait(lambda: ipc.get_shell_state()['taskbars'][0]['tray_menu'],'tray menu')
- ipc.click_at(menu['x']+80,menu['y']+8+30+15) # Pause all
- client.until(lambda r: r and r[0]['paused'],'tray Pause all')
- wait(lambda: not icons(),'paused transfers hide tray icon')
- client.send(op='remove',id=rows[0]['id']); client.until(lambda r:not r,'cleanup transfer')
- ipc.close_window(reopened['id']); wait(lambda:not windows(),'reopened Files closes')
- print('PASS: main-pane Transfers, folder and source row pause/resume, hover details, narrow layout, file selection, start and background tray')
- except Exception:
- print((tmp/"compositor.log").read_text(), file=sys.stderr)
- raise
- finally:
- if client:
- try:
- client.send(op='pause_all')
- client.until(lambda r:all(t['paused'] for t in r),'cleanup pauses work',5)
- except (OSError,AssertionError): pass
- client.close()
- if files: stop_process(files)
- stop_process(proc); log.close()
- # Helper exits after its final subscriber leaves, with no active work.
- wait(lambda:not (tmp/'files-transfers.sock').exists(),'helper exits',12)
-
-if __name__=='__main__':
- if '--private-bus' not in sys.argv:
- raise SystemExit(subprocess.call(['dbus-run-session','--',sys.executable,__file__,'--private-bus']))
- run()
diff --git a/tests/power.py b/tests/power.py
index 827433d..433fb6a 100644
--- a/tests/power.py
+++ b/tests/power.py
@@ -948,51 +948,6 @@ def test_prepare_for_shutdown_waits_for_sigterm(system_bus_address):
print("power: shutdown preparation preserves the session; SIGTERM exits without restarting Xwayland")
-def test_session_owned_helpers_stopped_on_logout(system_bus_address):
- """Quitting compositor (logout) sends SIGTERM to owned helpers, waits, and exits cleanly."""
- with tempfile.TemporaryDirectory(prefix="rediwm-power-test-") as directory:
- tmp = Path(directory)
- fake = start_fake({"FAKE_LOGIND_CAP": "yes"})
- try:
- process, log = spawn(tmp, system_bus_address)
- try:
- with IPCClient(tmp, timeout=15) as ipc:
- ipc.wait_for("wallpaper_presented", timeout_ms=10000)
- res = ipc.action("spawn", {"argv": ["/bin/sleep", "3600"]})
-
- def get_helper_pids():
- try:
- out = subprocess.check_output(["pgrep", "-f", "sleep 3600"], text=True)
- return [int(p) for p in out.strip().split() if p]
- except subprocess.CalledProcessError:
- return []
-
- wait_for(lambda: len(get_helper_pids()) > 0, "sleep helper running")
- helper_pids = get_helper_pids()
-
- try:
- press(ipc, "quit")
- except EOFError:
- pass # Quit can close IPC before its reply is flushed.
-
- rc = process.wait(timeout=5)
- assert rc == 0, f"compositor exited with code {rc}"
- wait_for(lambda: "stopping 1 session-owned helper(s)" in log_text(tmp),
- "stopping owned helper logged")
- wait_for(lambda: "terminating compositor session" in log_text(tmp),
- "terminating session logged")
- wait_for(lambda: all(not is_pid_running(p) for p in helper_pids),
- "owned helper terminated")
- finally:
- if process.poll() is None:
- stop_process(process)
- log.close()
- finally:
- fake.terminate()
- fake.wait(timeout=3)
- print("power: session-owned helpers are stopped with SIGTERM and reaped on logout")
-
-
def test_compositor_clean_termination_on_sigterm(system_bus_address):
"""Compositor catches SIGTERM, terminates owned helpers, and exits cleanly with 0."""
with tempfile.TemporaryDirectory(prefix="rediwm-power-test-") as directory:
@@ -1020,8 +975,6 @@ def test_compositor_clean_termination_on_sigterm(system_bus_address):
assert rc == 0, f"compositor exited with code {rc}"
wait_for(lambda: "received SIGTERM; requesting clean termination" in log_text(tmp),
"SIGTERM receipt logged")
- wait_for(lambda: "stopping 1 session-owned helper(s)" in log_text(tmp),
- "stopping owned helper logged")
wait_for(lambda: all(not is_pid_running(p) for p in helper_pids),
"owned helper terminated")
finally:
@@ -1234,7 +1187,6 @@ def main():
test_only_one_request_is_pending_at_a_time(system_bus_address)
test_prepare_for_sleep_deactivates_and_restores_session(system_bus_address)
test_prepare_for_shutdown_waits_for_sigterm(system_bus_address)
- test_session_owned_helpers_stopped_on_logout(system_bus_address)
test_compositor_clean_termination_on_sigterm(system_bus_address)
test_stuck_helper_does_not_block_shutdown(system_bus_address)
diff --git a/tests/screenshot_tool.py b/tests/screenshot_tool.py
index 5c4d297..94118e6 100644
--- a/tests/screenshot_tool.py
+++ b/tests/screenshot_tool.py
@@ -143,48 +143,6 @@ def run(scale, displays="1"):
receiver.kill()
receiver.wait()
- # Shell panels survive the picker, cancellation, and saved
- # captures. Their focused key handlers must allow shortcuts.
- ipc.set_dnd(True)
- time.sleep(4)
- for panel, action in (("start_menu", "OpenStartMenu"),
- ("control_center", "OpenControlCenter"),
- ("power_menu", "OpenPowerMenu")):
- move(200, 200)
- ipc.action(action)
- time.sleep(.6)
- state = ipc.get_shell_state(output["name"])[panel]
- assert state and state["state"] == "open", (panel, state)
- before_panel = image("before-" + panel)
- open_picker()
- assert ipc.get_shell_state(output["name"])[panel]["state"] == "open", panel
- height = round(clean.height / scale)
- move(100, 180)
- ipc.pointer_button(272, True)
- move(300, height - 20)
- selection = image("over-taskbar-" + panel)
- edge = lambda v: int(v * scale + .5)
- assert selection.getpixel((edge(300), edge(height - 20))) == (255, 255, 255), "taskbar covered selection corner"
- ipc.key_press("Escape")
- ipc.pointer_button(272, False)
- assert ipc.get_shell_state(output["name"])[panel]["state"] == "open", panel
- previous = set(files())
- open_picker()
- click((width - 360) // 2 + 220, 45)
- saved = wait_for(lambda: set(files()) - previous, "panel screenshot was not saved")
- shot = Image.open(saved.pop()).convert("RGB")
- box = state["box"]
- x, y = box["x"] - output["x"], box["y"] - output["y"]
- bounds = (edge(x), edge(y), edge(x + box["width"]), edge(y + box["height"]))
- assert_pixels(shot.crop(bounds), before_panel.crop(bounds), panel + " changed in saved screenshot")
- assert ipc.get_shell_state(output["name"])[panel]["state"] == "open", panel
- previous = set(files())
- ipc.key_press("Print")
- saved = wait_for(lambda: set(files()) - previous, "panel swallowed Print")
- shot = Image.open(saved.pop()).convert("RGB")
- assert_pixels(shot.crop(bounds), before_panel.crop(bounds), panel + " changed on Print")
- ipc.key_press("Escape")
- time.sleep(.4)
assert process.poll() is None
print(f"screenshot tool scale {scale}, displays {displays}: passed")
except Exception:
diff --git a/tests/session_restart.py b/tests/session_restart.py
index 94bdd39..8b0533f 100644
--- a/tests/session_restart.py
+++ b/tests/session_restart.py
@@ -20,9 +20,10 @@ def run():
options = tmp / 'install_paths.zig'
options.write_text('pub const bin = ' + json.dumps(str(tmp)) + ';\n')
configured_restart = tmp / 'rediwm-restart'
- subprocess.run(['zig', 'build-exe', '-lc', '--dep', 'install_paths',
+ subprocess.run(['zig', 'build-exe', '-lc', '--dep', 'install_paths', '--dep', 'platform',
'-Mroot=' + str(ROOT / 'src/session_restart.zig'),
'-Minstall_paths=' + str(options),
+ '-Mplatform=' + str(ROOT / 'src/platform/mod.zig'),
'-femit-bin=' + str(configured_restart)], check=True)
binary = tmp / 'rediwm'
source = ROOT / 'zig-out/release-safe/bin/rediwm'