Skip to content

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

FreeBSD port: platform FreeBSD parts and the fixes from the second build log

oxydizer710dacf8c65a
diff --git a/AGENTS.md b/AGENTS.md
index 47d3067..46e3834 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -267,7 +267,7 @@ panel painting. The key rules:
`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_*`,
- `SO_PEERCRED`, `prctl`, `eventfd` flags or `/proc/self/exe` (C and C++: its
+ `SO_PEERCRED`, `prctl`, `eventfd` flags, `renameat2`, `statx` or `/proc/self/exe` (C and C++: its
`child.h`, `self_exe.h`, `peer.h`, `process.h`). Elsewhere call libc 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/`
@@ -277,9 +277,16 @@ panel painting. The key rules:
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
- `parseColor()` in comptime defaults.
+ `_GNU_SOURCE`. glibc's socket calls take a transparent union, FreeBSD's a
+ plain pointer: call `std.c.connect(fd, @ptrCast(&addr), len)` (also `bind`,
+ `getsockname`, `accept`, `recvfrom`), never `c.connect` with
+ `.__sockaddr__`. Other differences that break FreeBSD's translation:
+ `c.SIG_IGN`/`SIG_DFL` (use `platform.process.ignoreBrokenPipes` and
+ `defaultSignal`), `mode_t` is 16 bits (`@intCast` into `chmod`, `mkdir`,
+ `fchmod`; shift with `std.math.Log2Int(c.mode_t)`), and glibc-only names
+ (`_NL_*`, `statx`, `renameat2`, `CLOCK.BOOTTIME`) need `@hasDecl` or a
+ `platform` function. Never translate glib/gobject/gio/librsvg;
+ hand-declare the ABI. No runtime `parseColor()` in comptime defaults.
* `std.os.linux.*` return `-errno` in `usize` (`std.os.linux.errno`);
`std.posix.system.*` are libc (`std.posix.errno`).
* **wlroots bindings** live in `src/wlr/`, backed by one translation of
diff --git a/build.zig b/build.zig
index cc2108c..4e4461f 100644
--- a/build.zig
+++ b/build.zig
@@ -24,7 +24,9 @@ pub fn build(b: *std.Build) void {
const layout = @import("build/install_paths.zig").Layout.init(b);
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
- const use_llvm = b.option(bool, "llvm", "Use LLVM and LLD (default for optimized builds)") orelse (optimize != .debug);
+ // On FreeBSD the self-hosted backend's executables lack crt1's `environ`, which libc.so.7 needs
+ // (a Debug rediwm-cursorgen died at startup, its ReleaseSafe build did not), so LLVM is the default there.
+ const use_llvm = b.option(bool, "llvm", "Use LLVM and LLD (default for optimized builds and on FreeBSD)") orelse (optimize != .debug or target.result.os.tag == .freebsd);
// Debug aid (TESTING.md): redraw every frame whole and log what the damage missed.
const damage_audit = b.option(bool, "damage-audit", "Compare every frame with a full repaint and log the difference (slow)") orelse false;
// Debug aid: log the timing of every frame (event, render, commit, presentation).
@@ -220,6 +222,9 @@ pub fn build(b: *std.Build) void {
// 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),
+ // rediwm-session and rediwm-dm still run on signalfd, epoll, pidfd and Linux VT ioctls; the FreeBSD
+ // port starts the compositor from the console (docs/plans/freebsd.md, D2 and phase 2).
+ .login_session = b.option(bool, "login-session", "Build and install rediwm-session and rediwm-dm (default: on, except on FreeBSD)") orelse (target.result.os.tag != .freebsd),
.i18n_tool = i18n_tool,
.wayland = wayland,
.xkbcommon = xkbcommon,
diff --git a/build/context.zig b/build/context.zig
index b585bd0..4bf675a 100644
--- a/build/context.zig
+++ b/build/context.zig
@@ -11,6 +11,7 @@ pub const Context = struct {
optimize: std.lang.Optimize,
use_llvm: bool,
transfers: bool,
+ login_session: bool,
wlroots_prefix: ?[]const u8,
i18n_tool: *std.Build.Step.Compile,
wayland: *std.Build.Module,
diff --git a/build/session.zig b/build/session.zig
index ba20001..6ffaaca 100644
--- a/build/session.zig
+++ b/build/session.zig
@@ -9,7 +9,8 @@ pub const Session = struct {
ws_mod: *std.Build.Module,
};
-/// rediwm-session, rediwm-dm and the accounts helper.
+/// rediwm-session, rediwm-dm and the accounts helper. The first two are always
+/// described (tests and other steps name them) but installed only with `login_session`.
pub fn add(ctx: Context) Session {
const b = ctx.b;
const target = ctx.target;
@@ -31,7 +32,7 @@ pub fn add(ctx: Context) Session {
session_supervisor.root_module.addImport("wayland", wayland);
session_supervisor.root_module.linkSystemLibrary("wayland-server", .{});
if (wlroots_prefix != null) session_supervisor.root_module.addRPathSpecial("$ORIGIN/../lib/rediwm");
- b.installArtifact(session_supervisor);
+ if (ctx.login_session) b.installArtifact(session_supervisor);
const restart = b.addExecutable(.{
.name = "rediwm-restart",
@@ -81,7 +82,7 @@ pub fn add(ctx: Context) Session {
dm.root_module.addImport("wayland_sessions", ws_mod);
dm.root_module.linkSystemLibrary("pam", .{});
dm.root_module.addCSourceFile(.{ .file = b.path("src/dm/pam.c"), .flags = &.{"-std=c11"} });
- b.installArtifact(dm);
+ if (ctx.login_session) b.installArtifact(dm);
b.step("rediwm-dm", "Build the display manager").dependOn(&dm.step);
const accounts_helper = b.addExecutable(.{
diff --git a/build/tests.zig b/build/tests.zig
index 7218129..5cf085a 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -270,7 +270,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
dm_tests.root_module.linkSystemLibrary("pam", .{});
dm_tests.root_module.addCSourceFile(.{ .file = b.path("src/dm/pam.c"), .flags = &.{"-std=c11"} });
const run_dm_tests = b.addRunArtifact(dm_tests);
- test_step.dependOn(&run_dm_tests.step);
+ if (ctx.login_session) test_step.dependOn(&run_dm_tests.step);
const dm_step = b.step("test-dm", "Run unit tests for rediwm-dm");
dm_step.dependOn(&run_dm_tests.step);
@@ -283,7 +283,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
session_tests.root_module.addImport("wayland", wayland);
session_tests.root_module.linkSystemLibrary("wayland-server", .{});
const run_session_tests = b.addRunArtifact(session_tests);
- test_step.dependOn(&run_session_tests.step);
+ if (ctx.login_session) test_step.dependOn(&run_session_tests.step);
const rediwm_session_step = b.step("test-rediwm-session", "Test the login supervisor's publication, crash-restart loop and bus calls");
rediwm_session_step.dependOn(&run_session_tests.step);
const rediwm_session_integration = b.addSystemCommand(&.{"python3"});
diff --git a/docs/plans/freebsd.md b/docs/plans/freebsd.md
index 266f59f..794d5ef 100644
--- a/docs/plans/freebsd.md
+++ b/docs/plans/freebsd.md
@@ -1,8 +1,9 @@
# FreeBSD support plan
Status: draft, 2026-11-05. The Linux-side preparation (P.1–P.4, P.7–P.10) is
-done, P.5 and P.6 are open, and no FreeBSD code exists yet. Decisions D1–D6
-are open.
+done, P.5 and P.6 are open. The FreeBSD parts of `platform` are written and
+the whole tree cross-compiles for `x86_64-freebsd` (Debug, ReleaseSafe, tests;
+see Validation), but nothing has run on FreeBSD yet. Decisions D1–D6 are open.
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
@@ -16,42 +17,56 @@ harfbuzz, fontconfig, librsvg, gio, CUPS, libarchive, D-Bus, polkit,
xdg-desktop-portal, pulseaudio and OpenPAM are in ports. Zig 0.17 targets
`x86_64-freebsd`. Night light rides wlroots' DRM gamma and should port as is.
-Our own code had no OS abstraction. 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.
+Our own code had no OS abstraction. It now lives in `src/platform/` (child
+handles, file watching, own path, peer credentials, process attributes, wake
+descriptors, rename and stat, seccomp filters, tool lookup, with C headers
+beside it), with a FreeBSD half for each part except seccomp. About 15 files
+still use `std.os.linux` outside it (the supervisor, the DM, the Files
+folder-size walk, `Output.zig`, the seccomp policy tables). What is left is
+the Linux-only interfaces below, sandboxes, services and the login manager.
A first outside build (FreeBSD 15.1-RELEASE amd64, AMD Navi 44 on drm-kmod,
Zig 0.17.1, wlroots 0.20 from ports `x11-toolkits/wlroots020`) built 72 of 114
-steps. Every failure was a known item or a missing package and is fixed on the
+steps. Every failure was a known item or a missing package and was fixed on the
Linux side (P.8–P.10; the transfers helper is off by default on FreeBSD).
+The second build of the same tester (14 failed of 106 Debug steps) stopped at
+the parts that P.4 and P.9 had deliberately made refuse to build off Linux,
+plus what that exposed: `c.SIG_IGN` does not translate, glibc's socket-address
+union, 16-bit `mode_t`, `landlock.h`, `pty.h`, `MADV_DONTDUMP`, `pam_start_confdir`,
+`_NL_*` locale items, `CLOCK_BOOTTIME`, netlink uevents, `renameat2` and
+`statx`, xattr calls, and the D-Bus control-message data offset (FreeBSD's
+`cmsghdr` is 12 bytes, its data starts at 16). All are fixed except what the
+next paragraph lists.
On 15.1 `sys/inotify.h`, `sys/timerfd.h`, `sys/eventfd.h` and `cr_pid` in
-`sys/ucred.h` exist (header checks only). 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.
+`sys/ucred.h` exist (header checks only). Not known yet: `memfd_create`, the
+transfers helper's C++ flags under clang and libc++, whether `cr_pid` is filled
+for a unix-socket peer, whether the kqueue child handles behave in the Wayland
+loop (libepoll-shim), and whether a DRM session or the headless GLES2 path
+works. The second tester log also showed a Debug `rediwm-cursorgen` dying with
+`Undefined symbol "environ"` while its ReleaseSafe build ran, so the build now
+defaults to LLVM on FreeBSD; confirm it. Two tests failed at run time: the
+D-Bus fd test (fixed, the offset above) and the images decoder test (probably
+a gdk-pixbuf port without the PNM loader; the test now skips there).
### Interfaces still to port
| Linux interface | Where | FreeBSD |
| --- | --- | --- |
-| 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. |
+| pidfd (`platform.child` `Handle`, `Set`; `child.h`). **Zig side done** (`child_freebsd.zig`); `child.h` is Linux only and the terminal that uses it refuses to start | `session/child`, supervisor, dm, IPC, `Toplevel`, pickers, System Monitor, terminal engine | kqueue `EVFILT_PROC`/`NOTE_EXIT`, its fd joining the wl loop like a pidfd. Signals by pid, guarded by the unreaped zombie, which holds only for our own children: handles on other processes (`Toplevel` client pids, IPC peers, System Monitor) need another identity check (start time from `kern.proc`). `Handle.pid()` (fdinfo) has no counterpart. |
| `signalfd`, `epoll` | supervisor, dm, `child.Set` | kqueue `EVFILT_SIGNAL`, kqueue. |
-| `inotify` (`platform.watch`) | 7 users | Native on 15; on 14.x kqueue `EVFILT_VNODE` has no names, so diff the directory. |
-| `eventfd` (`platform.wake`) | 9 sites | Native (13+); the flag values differ. |
+| `inotify` (`platform.watch`) | 7 users | Native on 15 (**done**, libc); on 14.x kqueue `EVFILT_VNODE` has no names, so diff the directory. |
+| `eventfd` (`platform.wake`) | 9 sites | Native (13+); the flag values differ (**done**). |
| `memfd_create`, `timerfd` | few | `sys/timerfd.h` on 15.1; confirm `memfd_create` in phase 0. |
-| `prctl` (`platform.process`, `process.h`) | dm worker, lock, PAM worker, PDF, theme helper, supervisor subreaper | `procctl` (`PROC_PDEATHSIG_CTL`, `PROC_NO_NEW_PRIVS_CTL`, `PROC_TRACE_CTL`, `PROC_REAP_ACQUIRE`), `pthread_set_name_np`. |
-| `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. |
+| `prctl` (`platform.process`, `process.h`) | dm worker, lock, PAM worker, PDF, theme helper, supervisor subreaper | `procctl` (`PROC_PDEATHSIG_CTL`, `PROC_NO_NEW_PRIVS_CTL`, `PROC_TRACE_CTL`, `PROC_REAP_ACQUIRE`), `pthread_set_name_np` (**done**). |
+| `SO_PEERCRED` (`platform.peer`, `peer.h`) | IPC (uid and pid, for sandbox allowances), `session_restart`, `files/torrents`, torrent helper, `bash.c` | `getsockopt(LOCAL_PEERCRED)` into `struct xucred` (**done**; a peer with `cr_pid` 0 is refused). Check at run time that `cr_pid` is filled for a unix-socket peer. `files/terminal/engine.c` authenticates each shell message with `SCM_CREDENTIALS`; FreeBSD's `SCM_CREDS` is sender-attached, so `bash.c` would send it too: decide when the port reaches the terminal. |
+| `/proc/self/exe` (`platform.exe`, `self_exe.h`) | Zig sites, `bass.c`, torrent helper, dm re-exec | `KERN_PROC_PATHNAME` (**done**; the re-exec uses the path, not a descriptor kept from startup). |
+| `statx`, `getdents64`, `dirent64` | Files folder sizes, IPC socket check, `session_restart` | `fstatat` behind `platform.fs.stat` (**done** for the IPC socket check and `session_restart`). The folder-size walk still reads with `getdents64`: it refuses on FreeBSD (`getdirentries` or `readdir`, to do). |
| `/proc/self/fd`, `fdinfo` | spawn paths; fd-as-path opens in `files/properties`, `pdf/print.c`, `pdf/sandbox.c`, `files/terminal/child.c` | `closefrom` for spawn paths; the path form needs `fdescfs` or `*at` calls on the fd, per site. |
| `/proc/<pid>/…`, `/proc/stat`, `/proc/meminfo` | system monitor, `ipc/processes.zig`, `placeholder_match` (parent chain), `session_restart` (exe), `detectSandbox` (`root/.flatpak-info`; no Flatpak on FreeBSD, expect "not sandboxed"), editor memory probe, supervisor teardown tree | 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 | `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. |
+| `pty.h`, `SCM_CREDENTIALS`, `/proc` walks | terminal engine | `libutil.h` is included and `util` linked, but `ft_start` refuses on FreeBSD: porting the shell channel's per-message check and the session teardown walk (`kern.proc` by session) needs a FreeBSD to test on. |
+| `renameat2` | ~9 sites: Files ops, Editor, Images, screenshots, desktop watcher, theme helper, torrent helper | `link` + `unlink` for no-replace, behind `platform.fs.renameNoReplace` (**done** for the Zig sites; the theme helper's `RENAME_EXCHANGE` and the transfers helper stay Linux only). |
+| `DRM_IOCTL_VERSION` | `Output.zig` | libdrm `drmGetVersion`; skipped on FreeBSD for now (only a hypervisor-GPU workaround). |
+| netlink `KOBJECT_UEVENT` | printer hotplug (`printing/client.zig`) | devd's seqpacket socket, or rescans only (rescans only, **done**). |
| `gettid`; `fork`, `kill`, `wait4`, `poll` loops | `thumbs`; supervisor and dm | A `platform` wrapper; the loops are replaced in phases 2 and 4. |
### Sandboxes
@@ -64,7 +79,9 @@ have no FreeBSD counterpart short of a rewrite on **Capsicum** (`cap_enter`,
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.
+closed (`rediwm_pdf_sandbox_enter` and the theme helper's `parser_sandbox`
+return `ENOTSUP` there; the PDF viewer opens nothing and theme packs cannot be
+imported).
### System services
@@ -181,11 +198,11 @@ 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`); 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
+`src/platform/` has its FreeBSD parts and the tree cross-compiles; what
+is left is to run it. `rediwm-session` and `rediwm-dm` are not built on
+FreeBSD (`-Dlogin-session`, default off there) until phases 2 and 4. Hide NM,
+BlueZ, PPD, UDisks, app scopes; PDF and theme helper refuse (done); the
+Files folder-size column stays empty and its terminal refuses. List the FreeBSD packages the build needs (the outside build stopped
on a missing `libtorrent-rasterbar`). Goal: `rediwm` and the apps start in a
seatd session and the headless integration suites run.
@@ -242,3 +259,11 @@ whatever the target, so hide it, and give Zig private caches:
On a root that still includes `linux/netlink.h` it fails with the outside
tester's error. It covers `libc.h` only: the roots that need cairo, libinput or
wlroots headers need FreeBSD's own, and Zig's headers may be older than 15.1.
+
+The whole build can be cross-checked the same way, to catch the next layer of
+errors before the tester does (Zig reports errors only in code it reaches, so
+fixes expose more): `tools/freebsd-cross/check.sh` (see its README). A pass
+means every unit compiled and the build reached the link; it cannot show
+header-version differences, library versions or anything that runs. The only
+errors it leaves are `undefined symbol`s from its empty libraries, so watch
+that list for names libc itself would own (`xattr` was one).
diff --git a/src/Output.zig b/src/Output.zig
index 26c9929..ea2deac 100644
--- a/src/Output.zig
+++ b/src/Output.zig
@@ -224,6 +224,8 @@ fn virtualGpuDriver(wlr_output: *wlr.Output) ?[]const u8 {
desc_len: usize = 0,
desc: ?[*]u8 = null,
};
+ // The request number below is Linux's ioctl encoding; the virtual-GPU drivers listed are Linux's too.
+ if (comptime @import("builtin").os.tag != .linux) return null;
const DRM_IOCTL_VERSION = std.os.linux.IOCTL.IOWR('d', 0x00, Version);
var name: [32]u8 = undefined;
var version: Version = .{ .name_len = name.len, .name = &name };
diff --git a/src/calculator/client.zig b/src/calculator/client.zig
index 89eab99..3c4538d 100644
--- a/src/calculator/client.zig
+++ b/src/calculator/client.zig
@@ -1,6 +1,7 @@
//! Standalone Calculator Wayland host (following the native Calculator client). Uses the same decoration, input,
//! cursor and released-buffer lifecycle as the other native RediWM clients.
const std = @import("std");
+const platform = @import("platform");
const ClientCursor = @import("ui").client_cursor;
const wl = @import("wayland").client.wl;
const xdg = @import("wayland").client.xdg;
@@ -755,7 +756,7 @@ const Buffer = struct {
};
pub fn run(init: std.process.Init) !void {
- _ = c.signal(c.SIGPIPE, c.SIG_IGN);
+ platform.process.ignoreBrokenPipes();
defer @import("../files/settings.zig").deinitTheme();
var watch = try @import("../system_monitor/settings_watch.zig").Watch.init(init.io, init.minimal.environ);
defer watch.deinit();
diff --git a/src/control_center/sections/region.zig b/src/control_center/sections/region.zig
index 6c94eb8..fa3f274 100644
--- a/src/control_center/sections/region.zig
+++ b/src/control_center/sections/region.zig
@@ -227,6 +227,16 @@ fn localeName(cc: *panel.ControlCenter, category: []const u8) []const u8 {
return "C";
}
+/// glibc's locale-name items. Other C libraries have none: the label is then
+/// the bare locale name.
+fn nlItem(comptime name: []const u8) ?c.nl_item {
+ return if (@hasDecl(c, name)) @field(c, name) else null;
+}
+
+/// Whether the locale has a currency at all: glibc names the international
+/// symbol, POSIX the local one.
+const currency_item: c.nl_item = if (@hasDecl(c, "INT_CURR_SYMBOL")) c.INT_CURR_SYMBOL else c.CRNCYSTR;
+
fn localeLabel(a: std.mem.Allocator, name: []const u8, item: c.nl_item) ![]const u8 {
const name_z = try a.dupeSentinel(u8, name, 0);
const locale = c.newlocale(c.LC_ALL_MASK, name_z, null) orelse return name;
@@ -277,7 +287,7 @@ fn previews(a: std.mem.Allocator, prefs: config.loader.RegionConfig) !W {
try info(a, tr("Date"), try a.dupe(u8, std.mem.sliceTo(&date, 0))),
try info(a, tr("Time"), try a.dupe(u8, std.mem.trim(u8, std.mem.sliceTo(&time, 0), " "))),
try info(a, tr("Number"), if (number_len > 0 and number_len < number.len) try a.dupe(u8, std.mem.sliceTo(&number, 0)) else tr("Unavailable")),
- try info(a, tr("Currency"), if (std.mem.span(c.nl_langinfo_l(c.INT_CURR_SYMBOL, locale)).len == 0) tr("Not specified") else if (currency_len > 0) try a.dupe(u8, std.mem.trim(u8, std.mem.sliceTo(&currency, 0), " ")) else tr("Unavailable")),
+ try info(a, tr("Currency"), if (std.mem.span(c.nl_langinfo_l(currency_item, locale)).len == 0) tr("Not specified") else if (currency_len > 0) try a.dupe(u8, std.mem.trim(u8, std.mem.sliceTo(&currency, 0), " ")) else tr("Unavailable")),
});
}
@@ -295,12 +305,12 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
const language = try card(a, &.{
panel.sectionTitle(tr("Language")),
text(tr("Application language"), 13, false),
- try choice(s, cc, a, "language", 1, s.locales.items, localeName(cc, "LC_MESSAGES"), c._NL_IDENTIFICATION_LANGUAGE),
+ try choice(s, cc, a, "language", 1, s.locales.items, localeName(cc, "LC_MESSAGES"), nlItem("_NL_IDENTIFICATION_LANGUAGE")),
});
const region = try card(a, &.{
panel.sectionTitle(tr("Region")),
text(tr("Regional formats"), 13, false),
- try choice(s, cc, a, "formats", 2, s.locales.items, localeName(cc, "LC_TIME"), c._NL_ADDRESS_COUNTRY_NAME),
+ try choice(s, cc, a, "formats", 2, s.locales.items, localeName(cc, "LC_TIME"), nlItem("_NL_ADDRESS_COUNTRY_NAME")),
try paragraph(a, tr("Date format for the taskbar; date, number and currency formats for new apps."), paragraph_width),
});
var toggle = try container(a, .row, &.{
diff --git a/src/dbus/connection_io.zig b/src/dbus/connection_io.zig
index 4c8351b..1c261cb 100644
--- a/src/dbus/connection_io.zig
+++ b/src/dbus/connection_io.zig
@@ -118,6 +118,11 @@ pub fn dispatch(self: *Connection, message: wire.Message) !void {
}
}
+/// Where a control message's data starts, CMSG_LEN(0): the header padded to
+/// the machine word. FreeBSD's header is 12 bytes and its data starts at 16,
+/// as on Linux, where the header is already 16.
+pub const cmsg_data = std.mem.alignForward(usize, @sizeOf(c.cmsghdr), @sizeOf(usize));
+
pub fn closeReadFds(self: *Connection) void {
for (self.read_fds[0..self.read_fd_count]) |fd| _ = c.close(fd);
self.read_fd_count = 0;
@@ -129,7 +134,7 @@ pub fn readWithFds(self: *Connection) !void {
const target = (try wire.frameLength(self.read_buf.items)) orelse 16;
var buf: [16384]u8 = undefined;
var iov: std.posix.iovec = .{ .base = &buf, .len = @min(buf.len, target - self.read_buf.items.len) };
- var control: [@sizeOf(c.cmsghdr) + 16 * @sizeOf(c_int)]u8 align(@alignOf(c.cmsghdr)) = undefined;
+ var control: [cmsg_data + 16 * @sizeOf(c_int)]u8 align(@alignOf(c.cmsghdr)) = undefined;
var msg: c.msghdr = std.mem.zeroes(c.msghdr);
msg.iov = @ptrCast(&iov);
msg.iovlen = 1;
@@ -147,7 +152,7 @@ pub fn readWithFds(self: *Connection) !void {
const header: *const c.cmsghdr = @ptrCast(@alignCast(&control[offset]));
if (header.len < @sizeOf(c.cmsghdr) or header.len > msg.controllen - offset) return error.InvalidReply;
if (header.level == std.posix.SOL.SOCKET and header.type == c.SCM.RIGHTS) {
- const data = control[offset + @sizeOf(c.cmsghdr) .. offset + header.len];
+ const data = control[@min(offset + cmsg_data, offset + header.len) .. offset + header.len];
const fds: []const c_int = std.mem.bytesAsSlice(c_int, @as([]align(@alignOf(c_int)) const u8, @alignCast(data)));
for (fds) |fd| {
if (self.read_fd_count == self.read_fds.len) {
diff --git a/src/dbus/connection_tests.zig b/src/dbus/connection_tests.zig
index 8377bfa..dadd643 100644
--- a/src/dbus/connection_tests.zig
+++ b/src/dbus/connection_tests.zig
@@ -3,6 +3,7 @@ const wl = @import("wayland").server.wl;
const c = std.posix.system;
const wire = @import("wire.zig");
const connection = @import("connection.zig");
+const io = @import("connection_io.zig");
const Connection = connection.Connection;
pub const TestResult = struct {
@@ -445,10 +446,10 @@ test "received FDs are frame scoped, cloexec, validated and closed after dispatc
var bytes = reply;
if (scenario == 2) bytes[40] = 1;
var iov: std.posix.iovec_const = .{ .base = &bytes, .len = bytes.len };
- var control: [std.mem.alignForward(usize, @sizeOf(c.cmsghdr) + @sizeOf(c_int), @sizeOf(usize))]u8 align(@alignOf(c.cmsghdr)) = @splat(0);
+ var control: [std.mem.alignForward(usize, io.cmsg_data + @sizeOf(c_int), @sizeOf(usize))]u8 align(@alignOf(c.cmsghdr)) = @splat(0);
const header: *c.cmsghdr = @ptrCast(&control);
- header.* = .{ .len = @sizeOf(c.cmsghdr) + @sizeOf(c_int), .level = std.posix.SOL.SOCKET, .type = c.SCM.RIGHTS };
- @as(*c_int, @ptrCast(@alignCast(&control[@sizeOf(c.cmsghdr)]))).* = sockets[1];
+ header.* = .{ .len = io.cmsg_data + @sizeOf(c_int), .level = std.posix.SOL.SOCKET, .type = c.SCM.RIGHTS };
+ @as(*c_int, @ptrCast(@alignCast(&control[io.cmsg_data]))).* = sockets[1];
var message: c.msghdr_const = std.mem.zeroes(c.msghdr_const);
message.iov = @ptrCast(&iov);
message.iovlen = 1;
diff --git a/src/desktop/watcher.zig b/src/desktop/watcher.zig
index d4cfd3f..1f22201 100644
--- a/src/desktop/watcher.zig
+++ b/src/desktop/watcher.zig
@@ -645,7 +645,7 @@ pub const Worker = struct {
defer a.free(p);
var stat: c.struct_stat = undefined;
if (c.stat(p, &stat) != 0 or stat.st_mode & c.S_IFMT != c.S_IFREG or stat.st_uid != c.getuid()) return error.NotYourFile;
- if (c.chmod(p, (stat.st_mode & 0o7777) | c.S_IXUSR) != 0) return error.PermissionChangeFailed;
+ if (c.chmod(p, @intCast((stat.st_mode & 0o7777) | c.S_IXUSR)) != 0) return error.PermissionChangeFailed;
},
.file => {
const p = try a.dupeSentinel(u8, cmd.path, 0);
@@ -659,7 +659,7 @@ pub const Worker = struct {
defer a.free(from);
const to = try a.dupeSentinel(u8, cmd.value, 0);
defer a.free(to);
- if (c.renameat2(c.AT_FDCWD, from, c.AT_FDCWD, to, 1) != 0) return error.RenameFailed;
+ platform.fs.renameNoReplace(from.ptr, to.ptr) catch return error.RenameFailed;
},
.link => {
const from = try a.dupeSentinel(u8, cmd.path, 0);
diff --git a/src/editor/drafts.zig b/src/editor/drafts.zig
index 4f0cdf0..42ecb0d 100644
--- a/src/editor/drafts.zig
+++ b/src/editor/drafts.zig
@@ -9,6 +9,7 @@
//! fight over it. Which tabs to keep and when to write is `app_drafts.zig`'s
//! business; nothing here knows about tabs or Wayland.
const std = @import("std");
+const platform = @import("platform");
const c = @import("../files/c.zig").api;
const op = @import("operation.zig");
const Document = @import("document.zig").Document;
@@ -311,9 +312,7 @@ pub fn catchSignals(wake: c_int) void {
}
pub fn releaseSignals() void {
- _ = c.signal(c.SIGTERM, c.SIG_DFL);
- _ = c.signal(c.SIGHUP, c.SIG_DFL);
- _ = c.signal(c.SIGINT, c.SIG_DFL);
+ inline for (.{ .TERM, .HUP, .INT }) |sig| platform.process.defaultSignal(sig);
signal_wake = -1;
}
diff --git a/src/editor/instance.zig b/src/editor/instance.zig
index e339887..8fea3b0 100644
--- a/src/editor/instance.zig
+++ b/src/editor/instance.zig
@@ -30,11 +30,11 @@ pub const Instance = struct {
const fd = c.socket(c.AF_UNIX, c.SOCK_DGRAM | c.SOCK_CLOEXEC | c.SOCK_NONBLOCK, 0);
if (fd < 0) return error.SocketFailed;
errdefer _ = c.close(fd);
- if (c.connect(fd, .{ .__sockaddr__ = @ptrCast(&address) }, @sizeOf(c.struct_sockaddr_un)) == 0) return .{ .fd = fd, .path = path, .primary = false };
+ if (std.c.connect(fd, @ptrCast(&address), @sizeOf(c.struct_sockaddr_un)) == 0) return .{ .fd = fd, .path = path, .primary = false };
const err = std.posix.errno(@as(c_int, -1));
if (err != .NOENT and err != .CONNREFUSED) return error.ConnectFailed;
_ = c.unlink(path);
- if (c.bind(fd, .{ .__sockaddr__ = @ptrCast(&address) }, @sizeOf(c.struct_sockaddr_un)) != 0) return error.BindFailed;
+ if (std.c.bind(fd, @ptrCast(&address), @sizeOf(c.struct_sockaddr_un)) != 0) return error.BindFailed;
_ = c.chmod(path, 0o600);
return .{ .fd = fd, .path = path, .primary = true };
}
diff --git a/src/editor/main.zig b/src/editor/main.zig
index a6cec6f..d2ab7fa 100644
--- a/src/editor/main.zig
+++ b/src/editor/main.zig
@@ -1,5 +1,6 @@
// Standalone text editor; decoration negotiation follows files/main.zig.
const std = @import("std");
+const platform = @import("platform");
const ClientCursor = @import("ui").client_cursor;
const wl = @import("wayland").client.wl;
const xdg = @import("wayland").client.xdg;
@@ -178,7 +179,7 @@ pub const Buffer = struct {
};
pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@import("instance.zig").Instance, initial_token: []const u8) !void {
- _ = c.signal(c.SIGPIPE, c.SIG_IGN);
+ platform.process.ignoreBrokenPipes();
const force_csd = init.minimal.environ.getPosix("REDIWM_EDITOR_FORCE_CSD") != null;
@import("../files/settings.zig").loadTheme(init.gpa, init.io, init.minimal.environ);
defer @import("../files/settings.zig").deinitTheme();
@@ -336,7 +337,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impo
const ms: c_int = @intCast(@min(wait, 60_000));
timeout = if (timeout < 0) ms else @min(timeout, ms);
}
- const result = c.poll(&fds, fd_count, self.app.caret.timeout(poll_now, self.clipboard.timeout(timeout)));
+ const result = c.poll(&fds, @intCast(fd_count), self.app.caret.timeout(poll_now, self.clipboard.timeout(timeout)));
if (result > 0 and (fds[0].revents & c.POLLIN != 0)) {
if (display.readEvents() != .SUCCESS) return error.DisplayFailed;
} else {
diff --git a/src/editor/operation.zig b/src/editor/operation.zig
index b790bad..e28e71f 100644
--- a/src/editor/operation.zig
+++ b/src/editor/operation.zig
@@ -13,31 +13,6 @@ const memory_check_floor: usize = 64 * 1024 * 1024;
/// A binary or non-UTF-8 file is refused after this many bytes, before the rest is read.
const sniff_len: usize = 64 * 1024;
const bom_bytes = "\xef\xbb\xbf";
-extern fn flistxattr(c_int, ?[*]u8, usize) isize;
-extern fn fgetxattr(c_int, [*:0]const u8, ?[*]u8, usize) isize;
-extern fn fsetxattr(c_int, [*:0]const u8, [*]const u8, usize, c_int) c_int;
-fn copyAttributes(source: c_int, destination: c_int) !void {
- const len = flistxattr(source, null, 0);
- if (len < 0) {
- if (std.posix.errno(@as(c_int, -1)) == .OPNOTSUPP) return;
- return error.MetadataFailed;
- }
- if (len == 0) return;
- if (len > 1024 * 1024) return error.MetadataFailed;
- const names = try a.alloc(u8, @intCast(len));
- defer a.free(names);
- if (flistxattr(source, names.ptr, names.len) != len) return error.FileChanged;
- var offset: usize = 0;
- while (offset < names.len) {
- const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(names.ptr + offset)), 0);
- const size = fgetxattr(source, name, null, 0);
- if (size < 0 or size > 1024 * 1024) return error.MetadataFailed;
- const value = try a.alloc(u8, @intCast(size));
- defer a.free(value);
- if (fgetxattr(source, name, value.ptr, value.len) != size or fsetxattr(destination, name, value.ptr, value.len, 0) != 0) return error.MetadataFailed;
- offset += name.len + 1;
- }
-}
pub const Stamp = struct {
dev: u64,
ino: u64,
@@ -251,7 +226,7 @@ pub const Operation = struct {
defer _ = c.close(source);
var source_stat: c.struct_stat = undefined;
if (c.fstat(source, &source_stat) != 0 or !before.?.eql(Stamp.of(source_stat))) return error.FileChanged;
- try copyAttributes(source, fd);
+ try platform.fs.copyAttributes(a, source, fd);
}
if (self.bom) try writeAll(fd, bom_bytes);
try writeAll(fd, self.bytes);
@@ -260,7 +235,7 @@ pub const Operation = struct {
var current: c.struct_stat = undefined;
if (c.stat(self.path, &current) != 0 or !stamp.eql(Stamp.of(current))) return error.FileChanged;
if (c.rename(temp, self.path) != 0) return error.WriteFailed;
- } else if (c.renameat2(c.AT_FDCWD, temp, c.AT_FDCWD, self.path, c.RENAME_NOREPLACE) != 0) return error.FileChanged;
+ } else platform.fs.renameNoReplace(temp, self.path) catch return error.FileChanged;
if (c.stat(self.path, &st) != 0) return error.WriteFailed;
self.stamp = Stamp.of(st);
const parent_z = try a.dupeSentinel(u8, parent, 0);
diff --git a/src/files/app_draw.zig b/src/files/app_draw.zig
index 167fa5b..046a0e7 100644
--- a/src/files/app_draw.zig
+++ b/src/files/app_draw.zig
@@ -142,7 +142,7 @@ pub fn formatPermissions(mode: c.mode_t) [10]u8 {
else => '?',
};
for (0..9) |i| {
- const bit = @as(c.mode_t, 0o400) >> @as(u5, @intCast(i));
+ const bit = @as(c.mode_t, 0o400) >> @as(std.math.Log2Int(c.mode_t), @intCast(i));
if (mode & bit != 0) result[i + 1] = "rwx"[i % 3];
}
if (mode & c.S_ISUID != 0) result[3] = if (mode & c.S_IXUSR != 0) 's' else 'S';
diff --git a/src/files/archive.zig b/src/files/archive.zig
index 89f2d7c..447c11c 100644
--- a/src/files/archive.zig
+++ b/src/files/archive.zig
@@ -303,7 +303,7 @@ pub fn extract(mem: Allocator, path: []const u8, destination: []const u8, member
}
}
// Keep ordinary executable bits, never set-id or archive ownership.
- if (member == null) _ = c.fchmod(fd, @as(c_uint, @intCast(a.archive_entry_perm(entry) & 0o777)) | 0o600);
+ if (member == null) _ = c.fchmod(fd, @intCast(@as(c_uint, @intCast(a.archive_entry_perm(entry) & 0o777)) | 0o600));
found = true;
if (member != null) break;
}
diff --git a/src/files/dirsize.zig b/src/files/dirsize.zig
index 8066845..e92ded5 100644
--- a/src/files/dirsize.zig
+++ b/src/files/dirsize.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const builtin = @import("builtin");
const c = @import("c.zig").api;
const linux = std.os.linux;
const Allocator = std.mem.Allocator;
@@ -211,6 +212,9 @@ pub const Pool = struct {
}
pub fn startJob(self: *Pool, path: []const u8) !*Job {
+ // The walk reads directories with statx and getdents64, which only Linux has; the folder
+ // size column stays empty elsewhere until the scan is ported (docs/plans/freebsd.md).
+ if (comptime builtin.os.tag != .linux) return error.Unsupported;
var path_buf: [4096]u8 = undefined;
const path_z = try std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0);
diff --git a/src/files/dirsize_tests.zig b/src/files/dirsize_tests.zig
index e26e798..eead664 100644
--- a/src/files/dirsize_tests.zig
+++ b/src/files/dirsize_tests.zig
@@ -1,6 +1,7 @@
//! Folder size tests: the dirsize walker and the App's folder size column.
const std = @import("std");
+const builtin = @import("builtin");
const history_mod = @import("history.zig");
const worker_mod = @import("worker.zig");
const app_mod = @import("app.zig");
@@ -35,6 +36,7 @@ pub fn countOpenFds() !usize {
}
test "dirsize: nested folders give the right total" {
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -86,6 +88,7 @@ test "dirsize: nested folders give the right total" {
}
test "dirsize: a hardlink pair is counted once" {
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -124,6 +127,7 @@ test "dirsize: a hardlink pair is counted once" {
}
test "dirsize: a symlink loop is not followed" {
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -162,6 +166,7 @@ test "dirsize: a symlink loop is not followed" {
}
test "dirsize: an unreadable folder gives a partial result" {
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -201,6 +206,7 @@ test "dirsize: an unreadable folder gives a partial result" {
}
test "dirsize: cancelling mid-walk leaks no fds" {
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -237,6 +243,7 @@ test "dirsize: cancelling mid-walk leaks no fds" {
}
test "dirsize: a mount boundary is not crossed" {
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
const pool = try dirsize_mod.Pool.init(a);
defer pool.deinit();
@@ -252,6 +259,7 @@ test "dirsize: a mount boundary is not crossed" {
}
test "App folder size calculation and display lifecycle" {
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
@@ -366,6 +374,7 @@ test "App size sort: calculated folders sort by apparent size, uncalculated last
}
test "App clicking dash starts calculation without changing selection" {
+ if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // the walk is Linux-only for now
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
const tmp = try makeTestDir(&tmp_buf);
diff --git a/src/files/main.zig b/src/files/main.zig
index 5d36ae9..64452b3 100644
--- a/src/files/main.zig
+++ b/src/files/main.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const platform = @import("platform");
const ClientCursor = @import("ui").client_cursor;
const wl = @import("wayland").client.wl;
const xdg = @import("wayland").client.xdg;
@@ -200,7 +201,7 @@ pub const Buffer = struct {
};
pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]const u8, chooser: ?@import("chooser.zig").Options, torrent_source: ?[]const u8, transfers: bool) !void {
- _ = c.signal(c.SIGPIPE, c.SIG_IGN);
+ platform.process.ignoreBrokenPipes();
const home_dir = init.minimal.environ.getPosix("HOME") orelse "/";
// Test-only escape hatch: skip decoration negotiation to exercise the
diff --git a/src/files/ops.zig b/src/files/ops.zig
index 4216e9d..5dd8fdf 100644
--- a/src/files/ops.zig
+++ b/src/files/ops.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const platform = @import("platform");
const i18n = @import("i18n");
const tr = i18n.tr;
const archive = @import("archive.zig");
@@ -102,13 +103,11 @@ pub fn renameItem(allocator: Allocator, old_path: []const u8, new_name: []const
const old_z = try allocator.dupeSentinel(u8, old_path, 0);
defer allocator.free(old_z);
- if (c.renameat2(c.AT_FDCWD, old_z, c.AT_FDCWD, new_path, 1) != 0) {
- return switch (std.c._errno().*) {
- c.EEXIST => error.PathAlreadyExists,
- c.EACCES => error.AccessDenied,
- else => error.RenameFailed,
- };
- }
+ platform.fs.renameNoReplace(old_z, new_path) catch |err| return switch (err) {
+ error.PathAlreadyExists => error.PathAlreadyExists,
+ error.AccessDenied => error.AccessDenied,
+ else => error.RenameFailed,
+ };
}
/// rm removes directory trees without following symlinks; -- protects option-like names.
@@ -292,7 +291,7 @@ pub fn copyRecursive(allocator: Allocator, src: []const u8, dst: []const u8, can
const dst_z = try allocator.dupeSentinel(u8, dst, 0);
defer allocator.free(dst_z);
- if (c.mkdir(dst_z, @as(c_uint, @intCast(st.st_mode & 0o7777))) != 0) return error.CreateDirectoryFailed;
+ if (c.mkdir(dst_z, @intCast(st.st_mode & 0o7777)) != 0) return error.CreateDirectoryFailed;
// Only remove a destination created by this operation on failure.
errdefer deleteRecursive(allocator, dst) catch {};
@@ -377,18 +376,11 @@ pub fn moveItem(allocator: Allocator, src: []const u8, dst: []const u8, cancel:
const dst_z = try allocator.dupeSentinel(u8, dst, 0);
defer allocator.free(dst_z);
- if (c.renameat2(c.AT_FDCWD, src_z, c.AT_FDCWD, dst_z, 1) == 0) {
- return;
- }
-
- const err = std.c._errno().*;
- if (err == c.EEXIST) {
- return error.PathAlreadyExists;
- } else if (err == c.EXDEV) {
- return crossDeviceMove(allocator, src, dst, cancel);
- } else {
- return error.RenameFailed;
- }
+ platform.fs.renameNoReplace(src_z, dst_z) catch |err| switch (err) {
+ error.PathAlreadyExists => return error.PathAlreadyExists,
+ error.CrossDevice => return crossDeviceMove(allocator, src, dst, cancel),
+ else => return error.RenameFailed,
+ };
}
pub const JobRunner = struct {
diff --git a/src/files/properties.zig b/src/files/properties.zig
index 5eb4632..1b07066 100644
--- a/src/files/properties.zig
+++ b/src/files/properties.zig
@@ -100,8 +100,12 @@ pub const State = struct {
const group = if (c.getgrgid(st.st_gid)) |gr| try a.dupe(u8, std.mem.span(gr.*.gr_name)) else try std.fmt.allocPrint(a, "{d}", .{st.st_gid});
errdefer a.free(group);
var result: State = .{ .allocator = a, .path = owned, .fd = fd, .stat = st, .description = description, .owner = owner, .group = group };
- var sx: c.struct_statx = undefined;
- if (c.statx(fd, "", c.AT_EMPTY_PATH | c.AT_SYMLINK_NOFOLLOW, c.STATX_BTIME, &sx) == 0 and sx.stx_mask & c.STATX_BTIME != 0) result.created = sx.stx_btime.tv_sec;
+ if (comptime @hasDecl(c, "struct_statx")) {
+ var sx: c.struct_statx = undefined;
+ if (c.statx(fd, "", c.AT_EMPTY_PATH | c.AT_SYMLINK_NOFOLLOW, c.STATX_BTIME, &sx) == 0 and sx.stx_mask & c.STATX_BTIME != 0) result.created = sx.stx_btime.tv_sec;
+ } else if (comptime @hasField(c.struct_stat, "st_birthtim")) {
+ result.created = st.st_birthtim.tv_sec; // FreeBSD's stat carries the creation time
+ }
if (preview) |im| result.preview = .{ .pixels = try a.dupe(u32, im.pixels), .size = im.size };
return result;
}
@@ -252,7 +256,7 @@ pub const State = struct {
};
fn permissionBit(index: usize) c.mode_t {
- return @as(c.mode_t, 1) << @as(u5, @intCast(8 - (index % 3) * 3 - index / 3));
+ return @as(c.mode_t, 1) << @as(std.math.Log2Int(c.mode_t), @intCast(8 - (index % 3) * 3 - index / 3));
}
fn date(timestamp: ?i64, buf: []u8) []const u8 {
diff --git a/src/files/terminal/engine.c b/src/files/terminal/engine.c
index a9534b3..227bded 100644
--- a/src/files/terminal/engine.c
+++ b/src/files/terminal/engine.c
@@ -8,7 +8,11 @@
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
+#ifdef __linux__
#include <pty.h>
+#else
+#include <libutil.h>
+#endif
#include <pwd.h>
#include <signal.h>
#include <spawn.h>
@@ -21,7 +25,15 @@
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
+#ifdef __linux__
#include "../../platform/child.h"
+#else
+/* Not ported (docs/plans/freebsd.md): ft_start refuses to run on this system,
+ * so there is never a terminal process to open, signal or close. */
+static inline int rediwm_child_open(pid_t pid) { (void)pid; return -1; }
+static inline int rediwm_child_signal(int handle, int sig) { (void)handle; (void)sig; return -1; }
+static inline void rediwm_child_close(int handle) { (void)handle; }
+#endif
#if VTERM_VERSION_MAJOR != 0 || VTERM_VERSION_MINOR != 3 || VTERM_VERSION_PATCH < 3
#error Files requires libvterm 0.3.3 (0.3 ABI)
@@ -195,6 +207,14 @@ static bool valid_shell(const char *path) {
}
int ft_start(FT *t, const char *helper, const char *plugin, const char *directory, bool scope) {
if (t->pid) return -1;
+#ifndef __linux__
+ /* The shell channel authenticates each message with SCM_CREDENTIALS and
+ * teardown walks /proc; neither exists here yet, and a terminal without
+ * them would be one the Files process cannot vouch for. */
+ (void)helper; (void)plugin; (void)directory; (void)scope;
+ t->error="The terminal is not available on this system yet";
+ return -1;
+#endif
const char *shell=getenv("SHELL");
char account_buf[16384]; struct passwd account, *found=NULL;
if (!valid_shell(shell)) {
@@ -206,8 +226,10 @@ int ft_start(FT *t, const char *helper, const char *plugin, const char *director
if (openpty(&master,&slave,NULL,NULL,&size)) goto failed;
if (fcntl(master,F_SETFD,FD_CLOEXEC) || fcntl(slave,F_SETFD,FD_CLOEXEC) ||
fcntl(master,F_SETFL,O_NONBLOCK) || socketpair(AF_UNIX,SOCK_SEQPACKET|SOCK_CLOEXEC|SOCK_NONBLOCK,0,pair)) goto failed;
+#ifdef __linux__
int one=1;
if (setsockopt(pair[0],SOL_SOCKET,SO_PASSCRED,&one,sizeof one)) goto failed;
+#endif
posix_spawn_file_actions_t actions;
if (posix_spawn_file_actions_init(&actions)) goto failed;
int rc=0;
@@ -259,6 +281,7 @@ static void flush_output(FT *t) {
if (written>0) { t->out_start+=(size_t)written; t->out_len-=(size_t)written; if (!t->out_len) t->out_start=0; }
else if (written<0 && errno!=EINTR && errno!=EAGAIN) t->out_len=0;
}
+#ifdef __linux__
static void integration(FT *t) {
for (int i=0;i<32 && t->channel>=0;i++) {
struct ft_status status;
@@ -283,6 +306,9 @@ static void integration(FT *t) {
if (t->request_queued && t->channel>=0 &&
send(t->channel,&t->request,sizeof t->request,MSG_DONTWAIT|MSG_NOSIGNAL)==sizeof t->request) t->request_queued=false;
}
+#else
+static void integration(FT *t) { (void)t; } /* no channel is ever opened (see ft_start) */
+#endif
/* A still-owned (possibly zombie) session leader reserves the session id, so
* these signals cannot hit a reused pid. Detached setsid jobs are independent.
* Runs only during session teardown, never on an idle or output path. */
diff --git a/src/files/thumbs.zig b/src/files/thumbs.zig
index 23f203f..9121a06 100644
--- a/src/files/thumbs.zig
+++ b/src/files/thumbs.zig
@@ -8,6 +8,7 @@
//! ARGB32. The cache is keyed by path and checked against the mtime and size
//! the folder listing reported, so an edited file misses and is re-requested.
const std = @import("std");
+const platform = @import("platform");
const c = @import("c.zig").api;
const decode = @import("thumb_decode.zig");
@@ -22,7 +23,6 @@ const max_results: usize = 32;
const worker_count = 2;
const worker_nice = 5;
-extern fn setpriority(which: c_int, who: c_uint, prio: c_int) c_int;
pub const Want = struct {
path: []const u8,
@@ -274,7 +274,7 @@ pub const Service = struct {
fn workerLoop(self: *Service, index: usize) void {
// Thumbnails are never urgent: yield to the UI and other programs.
- _ = setpriority(0, @intCast(std.os.linux.gettid()), worker_nice);
+ platform.process.lowerThreadPriority(worker_nice);
_ = c.pthread_mutex_lock(&self.mutex);
defer _ = c.pthread_mutex_unlock(&self.mutex);
while (!self.stopping) {
diff --git a/src/files/torrents.zig b/src/files/torrents.zig
index fbe4f59..fe44df4 100644
--- a/src/files/torrents.zig
+++ b/src/files/torrents.zig
@@ -64,7 +64,7 @@ pub const Client = struct {
_ = std.fmt.bufPrintSentinel(@ptrCast(&address.sun_path), "{s}/files-transfers.sock", .{runtime}, 0) catch return false;
const fd = c.socket(c.AF_UNIX, c.SOCK_SEQPACKET | c.SOCK_NONBLOCK | c.SOCK_CLOEXEC, 0);
if (fd < 0) return false;
- if (c.connect(fd, .{ .__sockaddr__ = @ptrCast(&address) }, @sizeOf(@TypeOf(address))) != 0) {
+ if (std.c.connect(fd, @ptrCast(&address), @sizeOf(@TypeOf(address))) != 0) {
_ = c.close(fd);
return false;
}
diff --git a/src/images/edit.zig b/src/images/edit.zig
index d58cafd..b6c491f 100644
--- a/src/images/edit.zig
+++ b/src/images/edit.zig
@@ -1,5 +1,6 @@
//! Pixel edits and background file operations. Originals are never overwritten.
const std = @import("std");
+const platform = @import("platform");
const c = @import("../files/c.zig").api;
const Image = @import("loader.zig").Image;
const Stamp = @import("cache.zig").Stamp;
@@ -48,10 +49,7 @@ fn save(im: Image, path: [:0]const u8) !void {
if (c.cairo_surface_status(surface) != c.CAIRO_STATUS_SUCCESS or c.cairo_surface_write_to_png_stream(surface, writePng, &fd) != c.CAIRO_STATUS_SUCCESS) return error.WriteFailed;
if (c.fsync(fd) != 0) return error.WriteFailed;
// Publish only a complete file, and never replace an existing destination.
- if (c.renameat2(c.AT_FDCWD, temp, c.AT_FDCWD, path, c.RENAME_NOREPLACE) != 0) {
- if (std.posix.errno(@as(c_int, -1)) == .EXIST) return error.PathAlreadyExists;
- return error.PublishFailed;
- }
+ platform.fs.renameNoReplace(temp, path) catch |err| return if (err == error.PathAlreadyExists) error.PathAlreadyExists else error.PublishFailed;
}
pub const Operation = struct {
diff --git a/src/images/main.zig b/src/images/main.zig
index 8bc6e65..739a71c 100644
--- a/src/images/main.zig
+++ b/src/images/main.zig
@@ -1,5 +1,6 @@
// Standalone image client; decoration negotiation follows files/main.zig.
const std = @import("std");
+const platform = @import("platform");
const ClientCursor = @import("ui").client_cursor;
const wl = @import("wayland").client.wl;
const xdg = @import("wayland").client.xdg;
@@ -811,7 +812,7 @@ const Buffer = struct {
};
pub fn run(init: std.process.Init, paths: []const [:0]const u8, selected: usize, return_focus: bool) !void {
- _ = c.signal(c.SIGPIPE, c.SIG_IGN);
+ platform.process.ignoreBrokenPipes();
const force_csd = init.minimal.environ.getPosix("REDIWM_IMAGES_FORCE_CSD") != null;
defer @import("../files/settings.zig").deinitTheme();
{
diff --git a/src/images_tests.zig b/src/images_tests.zig
index 52c5641..607db7f 100644
--- a/src/images_tests.zig
+++ b/src/images_tests.zig
@@ -62,7 +62,19 @@ test "streaming decoder enforces dimensions before full raster allocation" {
try std.testing.expect(fd >= 0);
defer _ = c.close(fd);
defer _ = c.unlink(&path);
- // PPM exposes dimensions in its header, before any pixel data arrives.
+ // PPM exposes dimensions in its header, before any pixel data arrives. Some
+ // gdk-pixbuf builds ship without the PNM loader (FreeBSD's port): a 1x1
+ // picture that cannot load there means the test has nothing to measure.
+ {
+ var probe = "/tmp/rediwm-images-probe-XXXXXX".*;
+ const probe_fd = c.mkstemp(&probe);
+ try std.testing.expect(probe_fd >= 0);
+ defer _ = c.close(probe_fd);
+ defer _ = c.unlink(&probe);
+ const tiny = "P6\n1 1\n255\n\x00\x00\x00";
+ try std.testing.expectEqual(@as(isize, tiny.len), c.write(probe_fd, tiny.ptr, tiny.len));
+ _ = loader.load(std.mem.sliceTo(&probe, 0), false) catch return error.SkipZigTest;
+ }
const header = "P6\n32769 1\n255\n";
try std.testing.expectEqual(@as(isize, header.len), c.write(fd, header.ptr, header.len));
const raster = @as([32769 * 3]u8, @splat(0));
diff --git a/src/ipc/server.zig b/src/ipc/server.zig
index 3a92bd5..5ca13ba 100644
--- a/src/ipc/server.zig
+++ b/src/ipc/server.zig
@@ -643,14 +643,11 @@ fn resolveSocketPath(allocator: std.mem.Allocator, wayland_display: []const u8)
/// as `$XDG_RUNTIME_DIR` does; the socket mode alone does not stop another
/// user from replacing it between sessions.
fn requirePrivateDir(dir: []const u8) IpcError!void {
- const linux = std.os.linux;
var buf: [108:0]u8 = undefined;
if (dir.len >= buf.len) return error.SocketPathTooLong;
@memcpy(buf[0..dir.len], dir);
buf[dir.len] = 0;
- 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;
+ const info = platform.fs.stat(&buf) orelse return error.NoRuntimeDir;
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/pdf/main.zig b/src/pdf/main.zig
index f9a6229..552a0ac 100644
--- a/src/pdf/main.zig
+++ b/src/pdf/main.zig
@@ -1,5 +1,6 @@
//! Wayland client lifecycle, buffer presentation, decoration negotiation and input loop for rediwm-pdf.
const std = @import("std");
+const platform = @import("platform");
const ClientCursor = @import("ui").client_cursor;
const wl = @import("wayland").client.wl;
const xdg = @import("wayland").client.xdg;
@@ -220,7 +221,7 @@ pub const Buffer = struct {
};
pub fn run(init: std.process.Init.Minimal) !void {
- _ = c.api.signal(c.api.SIGPIPE, c.api.SIG_IGN);
+ platform.process.ignoreBrokenPipes();
const args = init.args.vector;
if (args.len >= 2 and (std.mem.eql(u8, std.mem.span(args[1]), "--help") or std.mem.eql(u8, std.mem.span(args[1]), "-h"))) {
diff --git a/src/pdf/sandbox.c b/src/pdf/sandbox.c
index aa9f48c..4af6396 100644
--- a/src/pdf/sandbox.c
+++ b/src/pdf/sandbox.c
@@ -5,7 +5,9 @@
#include <errno.h>
#include <fcntl.h>
#include <iconv.h>
+#ifdef __linux__
#include <linux/landlock.h>
+#endif
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -15,11 +17,6 @@
#include <sys/syscall.h>
#include <unistd.h>
-// Keep the trusted password codec resident. Poppler GLib converts supplied
-// passwords to Latin-1; lazy gconv loading after Landlock would fail. This
-// handle processes no PDF bytes and is kept until process exit.
-static iconv_t password_codec = (iconv_t)-1;
-
int rediwm_pdf_open_document(const char *path) {
// NONBLOCK prevents an accidental FIFO/device argument from hanging us
// before we can check its type. The original inode is retained across
@@ -40,6 +37,12 @@ int rediwm_pdf_open_document(const char *path) {
return fd;
}
+#ifdef __linux__
+// Keep the trusted password codec resident. Poppler GLib converts supplied
+// passwords to Latin-1; lazy gconv loading after Landlock would fail. This
+// handle processes no PDF bytes and is kept until process exit.
+static iconv_t password_codec = (iconv_t)-1;
+
static int single_threaded(void) {
DIR *dir = opendir("/proc/self/task");
if (!dir) return -1;
@@ -161,3 +164,13 @@ int rediwm_pdf_sandbox_enter(int document, int display, int print) {
if (filesystem_policy() < 0) return -1;
return rediwm_pdf_syscall_policy(display);
}
+#else
+// No sandbox exists here yet (a Capsicum one is planned, docs/plans/freebsd.md,
+// P.5), and there is deliberately no unsandboxed fallback: the viewer refuses
+// to open any document.
+int rediwm_pdf_sandbox_enter(int document, int display, int print) {
+ (void)document; (void)display; (void)print;
+ errno = ENOTSUP;
+ return -1;
+}
+#endif
diff --git a/src/platform/AGENTS.md b/src/platform/AGENTS.md
index 5283e60..785ce8f 100644
--- a/src/platform/AGENTS.md
+++ b/src/platform/AGENTS.md
@@ -6,9 +6,13 @@ 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`/`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.
+`child.h`/`self_exe.h`/`peer.h`/`process.h` for C and C++, and `fs.zig`
+(rename without replacing, stat). Std only, no compositor imports. Linux and
+FreeBSD: a part is one file with a `switch (builtin.os.tag)` per function
+(`peer`, `process`, `wake`, `watch`, `exe`, `fs`), or a facade over
+`child_linux.zig` and `child_freebsd.zig`. A part not ported to another OS
+fails to compile there (`std.os.linux` would issue Linux syscall numbers on
+any target). FreeBSD notes are in `docs/plans/freebsd.md`.
* **A `Handle` is not a pid.** Hold it for as long as you may signal; a bare
`kill(pid)` is only safe while you have not reaped the child. `pid()` is
@@ -43,15 +47,24 @@ without changing callers.
`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.
+ `null` means refuse. `peer.h` needs `_GNU_SOURCE` on Linux (glibc hides
+ `SO_PEERCRED` without it). FreeBSD reads `LOCAL_PEERCRED`; a kernel that
+ leaves `cr_pid` 0 gives no answer, so the peer is refused.
+* **FreeBSD handles are kqueues** (`child_freebsd.zig`): readable once the
+ process exited and never drained, so `exited()` is a `poll`. `signal` refuses
+ after the exit event instead of trusting the pid; `peer` has no counterpart
+ and `pid()` cannot tell a reused number after a reap. `alive()` is false for
+ an unreaped zombie there, true on Linux.
+* **`fs.renameNoReplace` is atomic only on Linux.** FreeBSD hard-links and
+ unlinks (a failure leaves both names) and checks-then-renames a directory.
* Nothing here arms a timer or starts a thread; a caller retrying a failed
`add` owns that clock.
Still direct Linux calls (later steps of the plan): the supervisor's and the
DM's event loops and process calls (`signalfd`, `epoll`, `poll`, `fork`,
-`kill`, `wait4`), `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`.
+`kill`, `wait4`; neither program is built on FreeBSD), `statx` and `getdents64`
+in the Files folder-size walk (it refuses on other systems), `/proc` walks, the
+terminal's per-message `SCM_CREDENTIALS` check (`files/terminal/engine.c`, which
+refuses to start a terminal on other systems), the DRM driver ioctl in
+`Output.zig` and the two seccomp policy tables. Everything else outside this
+directory calls libc or `std.posix`.
diff --git a/src/platform/child.h b/src/platform/child.h
index 1c421d3..621cbba 100644
--- a/src/platform/child.h
+++ b/src/platform/child.h
@@ -5,6 +5,10 @@
#ifndef REDIWM_CHILD_H
#define REDIWM_CHILD_H
+#ifndef __linux__
+#error "platform/child.h is not ported to this OS yet (docs/plans/freebsd.md, phase 1)"
+#endif
+
#include <stddef.h>
#include <sys/syscall.h>
#include <sys/types.h>
diff --git a/src/platform/child.zig b/src/platform/child.zig
index 8bc1022..785a91d 100644
--- a/src/platform/child.zig
+++ b/src/platform/child.zig
@@ -1,10 +1,11 @@
//! Child processes by identity, not by pid. A `Handle` addresses the process
//! it was opened for even after the pid is reused, and its `fd` turns readable
//! when the process exits, without reaping it: the owner still collects the
-//! status with `reap`. Linux backs it with pidfds. Callers poll `fd` from the
-//! Wayland loop, `poll` or a `Set`; nothing here starts a thread or a timer.
+//! status with `reap`. Linux backs it with pidfds (`child_linux.zig`), FreeBSD
+//! with kqueue (`child_freebsd.zig`). Callers poll `fd` from the Wayland loop,
+//! `poll` or a `Set`; nothing here starts a thread or a timer.
const std = @import("std");
-const linux = std.os.linux;
+const builtin = @import("builtin");
pub const Pid = std.posix.pid_t;
pub const Signal = std.posix.SIG;
@@ -18,241 +19,19 @@ pub const Error = error{
Failed,
};
-fn classify(err: linux.E) Error {
- return switch (err) {
- .SRCH, .NOENT => error.NoSuchProcess,
- .PERM, .ACCES => error.PermissionDenied,
- .NOSYS, .INVAL => error.Unsupported,
- else => error.Failed,
- };
-}
-
-pub const Handle = struct {
- /// Readable once the process has exited; never carries data.
- fd: i32,
-
- /// Opens a handle on a running process. The caller closes it.
- pub fn open(process: Pid) Error!Handle {
- const rc = linux.pidfd_open(process, 0);
- if (linux.errno(rc) != .SUCCESS) return classify(linux.errno(rc));
- return .{ .fd = @intCast(rc) };
- }
-
- /// The handle of the process at the other end of a connected Unix socket,
- /// when the system can name it race-free. Null otherwise: fall back to
- /// `open` on the credentials' pid.
- pub fn peer(socket: i32) ?Handle {
- const so_peerpidfd = 77;
- var fd: i32 = -1;
- var len: u32 = @sizeOf(i32);
- const rc = linux.getsockopt(socket, linux.SOL.SOCKET, so_peerpidfd, @ptrCast(&fd), &len);
- if (linux.errno(rc) != .SUCCESS or fd < 0) return null;
- return .{ .fd = fd };
- }
-
- pub fn close(self: Handle) void {
- _ = linux.close(self.fd);
- }
-
- /// Signals the process this handle was opened for, never a pid reused
- /// since. Signal 0 only checks that it is still there.
- pub fn signal(self: Handle, sig: Signal) Error!void {
- const rc = linux.pidfd_send_signal(self.fd, sig, null, 0);
- if (linux.errno(rc) != .SUCCESS) return classify(linux.errno(rc));
- }
-
- pub fn alive(self: Handle) bool {
- self.signal(@enumFromInt(0)) catch return false;
- return true;
- }
-
- /// A nonblocking check of `fd`: has the process exited.
- pub fn exited(self: Handle) bool {
- var fds = [_]linux.pollfd{.{ .fd = self.fd, .events = linux.POLL.IN, .revents = 0 }};
- return linux.errno(linux.poll(&fds, 1, 0)) == .SUCCESS and fds[0].revents != 0;
- }
-
- /// The pid of the process this handle is on: null once it has exited and
- /// been reaped, even if the number was reused since. An unreaped zombie
- /// still has its pid (see `exited`). Unavailable when the system cannot say.
- pub fn pid(self: Handle) error{Unavailable}!?Pid {
- var path: [64]u8 = undefined;
- const name = std.fmt.bufPrintSentinel(&path, "/proc/self/fdinfo/{d}", .{self.fd}, 0) catch unreachable;
- const opened = linux.openat(linux.AT.FDCWD, name.ptr, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NOFOLLOW = true }, 0);
- if (linux.errno(opened) != .SUCCESS) return error.Unavailable;
- const info_fd: i32 = @intCast(opened);
- defer _ = linux.close(info_fd);
- var buf: [4096]u8 = undefined;
- var len: usize = 0;
- while (len < buf.len) {
- const rc = linux.read(info_fd, buf[len..].ptr, buf.len - len);
- switch (linux.errno(rc)) {
- .SUCCESS => {},
- .INTR => continue,
- else => return error.Unavailable,
- }
- if (rc == 0) break;
- len += rc;
- } else return error.Unavailable;
- var lines = std.mem.splitScalar(u8, buf[0..len], '\n');
- while (lines.next()) |line| {
- if (!std.mem.startsWith(u8, line, "Pid:")) continue;
- const value = std.fmt.parseInt(Pid, std.mem.trim(u8, line["Pid:".len..], " \t"), 10) catch return error.Unavailable;
- return if (value < 0) null else value;
- }
- return null;
- }
-};
-
-/// Collects the wait status of a child that has exited (or null: still
-/// running, or somebody else reaped it). Never blocks.
-pub fn reap(pid: Pid) ?u32 {
- var status: u32 = 0;
- while (true) {
- const rc = linux.wait4(pid, @ptrCast(&status), linux.W.NOHANG, null);
- switch (linux.errno(rc)) {
- .INTR => continue,
- .SUCCESS => return if (rc == pid) status else null,
- else => return null,
- }
- }
-}
-
-/// Whether a process with this pid exists right now. Racy by nature: the pid
-/// may be another process's by the time it matters; prefer a `Handle`.
-pub fn exists(pid: Pid) bool {
- return linux.errno(linux.kill(pid, @enumFromInt(0))) == .SUCCESS;
-}
-
-/// Signals every member of the process group `pgid`, a leader's own pid.
-pub fn signalGroup(pgid: Pid, sig: Signal) void {
- _ = linux.kill(-pgid, sig);
-}
-
-/// 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.
-pub const Set = struct {
- const Entry = struct { pid: Pid, handle: Handle };
- pub const Exit = struct { pid: Pid, status: ?u32 };
-
- /// Readable while `next` has an exit to report; -1 until the first `add`.
- fd: i32 = -1,
- entries: std.ArrayList(Entry) = .empty,
-
- pub fn add(self: *Set, allocator: std.mem.Allocator, pid: Pid) !void {
- try self.entries.ensureUnusedCapacity(allocator, 1);
- if (self.fd < 0) {
- const rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
- if (linux.errno(rc) != .SUCCESS) return error.Failed;
- self.fd = @intCast(rc);
- }
- const handle = try Handle.open(pid);
- errdefer handle.close();
- var event: linux.epoll_event = .{ .events = linux.EPOLL.IN, .data = .{ .fd = handle.fd } };
- if (linux.errno(linux.epoll_ctl(self.fd, linux.EPOLL.CTL_ADD, handle.fd, &event)) != .SUCCESS) return error.Failed;
- self.entries.appendAssumeCapacity(.{ .pid = pid, .handle = handle });
- }
-
- /// The next child that exited, reaped, or null when none has.
- pub fn next(self: *Set) ?Exit {
- if (self.fd < 0) return null;
- var events: [1]linux.epoll_event = undefined;
- const rc = linux.epoll_wait(self.fd, &events, 1, 0);
- if (linux.errno(rc) != .SUCCESS or rc == 0) return null;
- for (self.entries.items, 0..) |entry, i| {
- if (entry.handle.fd != events[0].data.fd) continue;
- _ = linux.epoll_ctl(self.fd, linux.EPOLL.CTL_DEL, entry.handle.fd, null);
- entry.handle.close();
- _ = self.entries.swapRemove(i);
- return .{ .pid = entry.pid, .status = reap(entry.pid) };
- }
- unreachable;
- }
-
- pub fn signalAll(self: *Set, sig: Signal) void {
- for (self.entries.items) |entry| entry.handle.signal(sig) catch {};
- }
-
- pub fn deinit(self: *Set, allocator: std.mem.Allocator) void {
- while (self.next() != null) {}
- for (self.entries.items) |entry| entry.handle.close();
- self.entries.deinit(allocator);
- if (self.fd >= 0) _ = linux.close(self.fd);
- self.* = .{};
- }
+const impl = switch (builtin.os.tag) {
+ .linux => @import("child_linux.zig"),
+ .freebsd => @import("child_freebsd.zig"),
+ else => @compileError("platform.child is not ported to this OS yet (docs/plans/freebsd.md, phase 1)"),
};
-fn waitReadable(fd: i32, timeout_ms: i32) bool {
- var fds = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.IN, .revents = 0 }};
- return linux.errno(linux.poll(&fds, 1, timeout_ms)) == .SUCCESS and fds[0].revents != 0;
-}
-
-test "a handle follows one process through signal, exit and reap" {
- const io = std.testing.io;
- var child = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
- const pid = child.id.?;
- const handle = try Handle.open(pid);
- defer handle.close();
- try std.testing.expect(handle.alive());
- try std.testing.expect(!handle.exited());
- try std.testing.expectEqual(@as(?Pid, pid), try handle.pid());
- try std.testing.expectEqual(@as(?u32, null), reap(pid));
-
- try handle.signal(.TERM);
- try std.testing.expect(waitReadable(handle.fd, 5000));
- try std.testing.expect(handle.exited());
- // The zombie keeps its pid until it is reaped; then the handle names nobody.
- try std.testing.expectEqual(@as(?Pid, pid), try handle.pid());
- const status = reap(pid).?;
- try std.testing.expect(linux.W.IFSIGNALED(status) and linux.W.TERMSIG(status) == .TERM);
- try std.testing.expectEqual(@as(?u32, null), reap(pid));
- try std.testing.expectEqual(@as(?Pid, null), try handle.pid());
- try std.testing.expectError(error.NoSuchProcess, handle.signal(.TERM));
- child.id = null;
-}
-
-test "a handle cannot be opened on a process that does not exist" {
- try std.testing.expectError(error.NoSuchProcess, Handle.open(std.math.maxInt(Pid)));
-}
+pub const Handle = impl.Handle;
+pub const Set = impl.Set;
+pub const reap = impl.reap;
+pub const exists = impl.exists;
+pub const signalGroup = impl.signalGroup;
+pub const killAndReap = impl.killAndReap;
-test "a set reports each exit once with its status and signals the rest" {
- const io = std.testing.io;
- var quick = try std.process.spawn(io, .{ .argv = &.{ "/bin/sh", "-c", "exit 3" } });
- var slow = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
- var set: Set = .{};
- defer set.deinit(std.testing.allocator);
- try set.add(std.testing.allocator, quick.id.?);
- try set.add(std.testing.allocator, slow.id.?);
- try std.testing.expect(waitReadable(set.fd, 5000));
- const first = set.next().?;
- try std.testing.expectEqual(quick.id.?, first.pid);
- try std.testing.expectEqual(@as(u8, 3), linux.W.EXITSTATUS(first.status.?));
- try std.testing.expect(set.next() == null);
- set.signalAll(.KILL);
- try std.testing.expect(waitReadable(set.fd, 5000));
- const second = set.next().?;
- try std.testing.expectEqual(slow.id.?, second.pid);
- try std.testing.expect(linux.W.IFSIGNALED(second.status.?));
- try std.testing.expectEqual(@as(usize, 0), set.entries.items.len);
- quick.id = null;
- slow.id = null;
+test {
+ _ = impl;
}
diff --git a/src/platform/child_freebsd.zig b/src/platform/child_freebsd.zig
new file mode 100644
index 0000000..b652bff
--- /dev/null
+++ b/src/platform/child_freebsd.zig
@@ -0,0 +1,272 @@
+//! FreeBSD backing of `child.zig`. FreeBSD has no pidfd, so a handle is a
+//! kqueue holding one `EVFILT_PROC`/`NOTE_EXIT` registration for the process:
+//! its descriptor turns readable when the process exits and stays readable,
+//! because nobody ever dequeues the event, and polls like any descriptor
+//! (the Wayland loop's epoll emulation included).
+//!
+//! The handle also keeps the pid, and signals go by pid. The guard against a
+//! reused pid is the exit event: once it is pending the handle refuses to
+//! signal. Before that the process still exists, and an unreaped child's pid
+//! cannot be reused. For a process that is not our child the window between
+//! its exit and our `signal` call is the only gap, and a pid takes a full
+//! wrap of the pid space to come back.
+const std = @import("std");
+const c = std.c;
+const child = @import("child.zig");
+
+const Pid = child.Pid;
+const Signal = child.Signal;
+const Error = child.Error;
+
+const Kevent = c.Kevent;
+
+fn classify(err: std.posix.E) Error {
+ return switch (err) {
+ .SRCH => error.NoSuchProcess,
+ .PERM, .ACCES => error.PermissionDenied,
+ .NOSYS, .INVAL => error.Unsupported,
+ else => error.Failed,
+ };
+}
+
+fn exitRegistration(process: Pid) Kevent {
+ return .{
+ .ident = @intCast(process),
+ .filter = c.EVFILT.PROC,
+ .flags = c.EV.ADD | c.EV.ENABLE,
+ .fflags = c.NOTE.EXIT,
+ .data = 0,
+ .udata = 0,
+ };
+}
+
+/// A new close-on-exec kqueue.
+fn newQueue() Error!i32 {
+ const kq = c.kqueue();
+ if (kq < 0) return classify(std.posix.errno(kq));
+ // FD_CLOEXEC is 1 (sys/fcntl.h).
+ _ = c.fcntl(kq, c.F.SETFD, @as(c_int, 1));
+ return kq;
+}
+
+/// Registers `process` for exit on `kq`. A process that exited but is not yet
+/// reaped (a zombie) registers fine and fires at once; a gone one is ESRCH.
+fn watchExit(kq: i32, process: Pid) Error!void {
+ const change = exitRegistration(process);
+ var none: [1]Kevent = undefined;
+ // With room for no events, a failed registration is the call's error.
+ if (c.kevent(kq, @ptrCast(&change), 1, &none, 0, null) < 0) return classify(std.posix.errno(@as(c_int, -1)));
+}
+
+fn pollIn(fd: i32, timeout_ms: i32) bool {
+ var fds = [_]c.pollfd{.{ .fd = fd, .events = c.POLL.IN, .revents = 0 }};
+ return c.poll(&fds, 1, timeout_ms) > 0 and fds[0].revents != 0;
+}
+
+pub const Handle = struct {
+ /// Readable once the process has exited; never carries data.
+ fd: i32,
+ /// The process this handle was opened for.
+ process: Pid,
+
+ /// Opens a handle on a running process. The caller closes it.
+ pub fn open(process: Pid) Error!Handle {
+ const kq = try newQueue();
+ errdefer _ = c.close(kq);
+ try watchExit(kq, process);
+ return .{ .fd = kq, .process = process };
+ }
+
+ /// FreeBSD cannot name the peer of a socket race-free: callers fall back
+ /// to `open` on the credentials' pid.
+ pub fn peer(socket: i32) ?Handle {
+ _ = socket;
+ return null;
+ }
+
+ pub fn close(self: Handle) void {
+ _ = c.close(self.fd);
+ }
+
+ /// Signals the process this handle was opened for, never a pid reused
+ /// since (see the file comment). Signal 0 only checks that it is still
+ /// there. A process that has exited is gone for this purpose, even while
+ /// its unreaped zombie still answers `kill`.
+ pub fn signal(self: Handle, sig: Signal) Error!void {
+ if (self.exited()) return error.NoSuchProcess;
+ if (c.kill(self.process, sig) != 0) return classify(std.posix.errno(@as(c_int, -1)));
+ }
+
+ pub fn alive(self: Handle) bool {
+ self.signal(@enumFromInt(0)) catch return false;
+ return true;
+ }
+
+ /// A nonblocking check of `fd`: has the process exited.
+ pub fn exited(self: Handle) bool {
+ return pollIn(self.fd, 0);
+ }
+
+ /// The pid of the process this handle is on: null once it has exited and
+ /// been reaped. An unreaped zombie still has its pid (see `exited`). The
+ /// kernel does not say whether a number was reused after the reap, so a
+ /// reaped child whose number a new process took reads as that pid.
+ pub fn pid(self: Handle) error{Unavailable}!?Pid {
+ if (!self.exited()) return self.process;
+ return if (c.kill(self.process, @enumFromInt(0)) == 0) self.process else null;
+ }
+};
+
+/// Collects the wait status of a child that has exited (or null: still
+/// running, or somebody else reaped it). Never blocks.
+pub fn reap(pid: Pid) ?u32 {
+ var status: c_int = 0;
+ while (true) {
+ const rc = c.waitpid(pid, &status, c.W.NOHANG);
+ if (rc == pid) return @bitCast(status);
+ if (rc < 0 and std.posix.errno(rc) == .INTR) continue;
+ return null;
+ }
+}
+
+/// Whether a process with this pid exists right now. Racy by nature: the pid
+/// may be another process's by the time it matters; prefer a `Handle`.
+pub fn exists(pid: Pid) bool {
+ return c.kill(pid, @enumFromInt(0)) == 0;
+}
+
+/// Signals every member of the process group `pgid`, a leader's own pid.
+pub fn signalGroup(pgid: Pid, sig: Signal) void {
+ _ = c.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 {
+ _ = c.kill(pid, .KILL);
+ var status: c_int = 0;
+ while (c.waitpid(pid, &status, 0) < 0 and std.posix.errno(@as(c_int, -1)) == .INTR) {}
+}
+
+/// 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. The members are children of this
+/// process, so their pids stay reserved until `next` reaps them.
+pub const Set = struct {
+ pub const Exit = struct { pid: Pid, status: ?u32 };
+
+ /// Readable while `next` has an exit to report; -1 until the first `add`.
+ fd: i32 = -1,
+ pids: std.ArrayList(Pid) = .empty,
+
+ pub fn add(self: *Set, allocator: std.mem.Allocator, pid: Pid) !void {
+ try self.pids.ensureUnusedCapacity(allocator, 1);
+ if (self.fd < 0) self.fd = try newQueue();
+ try watchExit(self.fd, pid);
+ self.pids.appendAssumeCapacity(pid);
+ }
+
+ /// The next child that exited, reaped, or null when none has.
+ pub fn next(self: *Set) ?Exit {
+ if (self.fd < 0) return null;
+ var events: [1]Kevent = undefined;
+ const now: c.timespec = .{ .sec = 0, .nsec = 0 };
+ // A NOTE_EXIT registration is one-shot: delivering it removes it.
+ if (c.kevent(self.fd, @ptrCast(&events), 0, &events, 1, &now) <= 0) return null;
+ const pid: Pid = @intCast(events[0].ident);
+ for (self.pids.items, 0..) |member, i| {
+ if (member != pid) continue;
+ _ = self.pids.swapRemove(i);
+ return .{ .pid = pid, .status = reap(pid) };
+ }
+ return null;
+ }
+
+ pub fn signalAll(self: *Set, sig: Signal) void {
+ for (self.pids.items) |pid| _ = c.kill(pid, sig);
+ }
+
+ pub fn deinit(self: *Set, allocator: std.mem.Allocator) void {
+ while (self.next() != null) {}
+ self.pids.deinit(allocator);
+ if (self.fd >= 0) _ = c.close(self.fd);
+ self.* = .{};
+ }
+};
+
+test "a child nobody watches is killed and collected" {
+ var child_process = try std.process.spawn(std.testing.io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ const pid = child_process.id.?;
+ killAndReap(pid);
+ child_process.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));
+}
+
+test "a handle follows one process through signal, exit and reap" {
+ const io = std.testing.io;
+ var child_process = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ const pid = child_process.id.?;
+ const handle = try Handle.open(pid);
+ defer handle.close();
+ try std.testing.expect(handle.alive());
+ try std.testing.expect(!handle.exited());
+ try std.testing.expectEqual(@as(?Pid, pid), try handle.pid());
+ try std.testing.expectEqual(@as(?u32, null), reap(pid));
+
+ try handle.signal(.TERM);
+ try std.testing.expect(pollIn(handle.fd, 5000));
+ try std.testing.expect(handle.exited());
+ // The zombie keeps its pid until it is reaped; then the handle names nobody.
+ try std.testing.expectEqual(@as(?Pid, pid), try handle.pid());
+ const status = reap(pid).?;
+ try std.testing.expect(std.posix.W.IFSIGNALED(status) and std.posix.W.TERMSIG(status) == Signal.TERM);
+ try std.testing.expectEqual(@as(?u32, null), reap(pid));
+ try std.testing.expectEqual(@as(?Pid, null), try handle.pid());
+ try std.testing.expectError(error.NoSuchProcess, handle.signal(.TERM));
+ child_process.id = null;
+}
+
+test "a handle cannot be opened on a process that does not exist" {
+ try std.testing.expectError(error.NoSuchProcess, Handle.open(std.math.maxInt(Pid)));
+}
+
+test "a handle sees an exit whether or not it happened before the handle opened" {
+ const io = std.testing.io;
+ var quick = try std.process.spawn(io, .{ .argv = &.{ "/bin/sh", "-c", "exit 0" } });
+ const pid = quick.id.?;
+ // Not reaped yet: the pid is still there, as a zombie once it has run.
+ const handle = try Handle.open(pid);
+ defer handle.close();
+ try std.testing.expect(pollIn(handle.fd, 5000));
+ try std.testing.expect(handle.exited());
+ const late = try Handle.open(pid);
+ defer late.close();
+ try std.testing.expect(late.exited());
+ try std.testing.expect(reap(pid) != null);
+ quick.id = null;
+}
+
+test "a set reports each exit once with its status and signals the rest" {
+ const io = std.testing.io;
+ var quick = try std.process.spawn(io, .{ .argv = &.{ "/bin/sh", "-c", "exit 3" } });
+ var slow = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ var set: Set = .{};
+ defer set.deinit(std.testing.allocator);
+ try set.add(std.testing.allocator, quick.id.?);
+ try set.add(std.testing.allocator, slow.id.?);
+ try std.testing.expect(pollIn(set.fd, 5000));
+ const first = set.next().?;
+ try std.testing.expectEqual(quick.id.?, first.pid);
+ try std.testing.expectEqual(@as(u8, 3), std.posix.W.EXITSTATUS(first.status.?));
+ try std.testing.expect(set.next() == null);
+ set.signalAll(.KILL);
+ try std.testing.expect(pollIn(set.fd, 5000));
+ const second = set.next().?;
+ try std.testing.expectEqual(slow.id.?, second.pid);
+ try std.testing.expect(std.posix.W.IFSIGNALED(second.status.?));
+ try std.testing.expectEqual(@as(usize, 0), set.pids.items.len);
+ quick.id = null;
+ slow.id = null;
+}
diff --git a/src/platform/child_linux.zig b/src/platform/child_linux.zig
new file mode 100644
index 0000000..9e1af5a
--- /dev/null
+++ b/src/platform/child_linux.zig
@@ -0,0 +1,248 @@
+//! Linux backing of `child.zig`: handles are pidfds, a `Set` is an epoll
+//! instance over them.
+const std = @import("std");
+const linux = std.os.linux;
+const types = @import("child.zig");
+
+const Pid = types.Pid;
+const Signal = types.Signal;
+const Error = types.Error;
+
+fn classify(err: linux.E) Error {
+ return switch (err) {
+ .SRCH, .NOENT => error.NoSuchProcess,
+ .PERM, .ACCES => error.PermissionDenied,
+ .NOSYS, .INVAL => error.Unsupported,
+ else => error.Failed,
+ };
+}
+
+pub const Handle = struct {
+ /// Readable once the process has exited; never carries data.
+ fd: i32,
+
+ /// Opens a handle on a running process. The caller closes it.
+ pub fn open(process: Pid) Error!Handle {
+ const rc = linux.pidfd_open(process, 0);
+ if (linux.errno(rc) != .SUCCESS) return classify(linux.errno(rc));
+ return .{ .fd = @intCast(rc) };
+ }
+
+ /// The handle of the process at the other end of a connected Unix socket,
+ /// when the system can name it race-free. Null otherwise: fall back to
+ /// `open` on the credentials' pid.
+ pub fn peer(socket: i32) ?Handle {
+ const so_peerpidfd = 77;
+ var fd: i32 = -1;
+ var len: u32 = @sizeOf(i32);
+ const rc = linux.getsockopt(socket, linux.SOL.SOCKET, so_peerpidfd, @ptrCast(&fd), &len);
+ if (linux.errno(rc) != .SUCCESS or fd < 0) return null;
+ return .{ .fd = fd };
+ }
+
+ pub fn close(self: Handle) void {
+ _ = linux.close(self.fd);
+ }
+
+ /// Signals the process this handle was opened for, never a pid reused
+ /// since. Signal 0 only checks that it is still there.
+ pub fn signal(self: Handle, sig: Signal) Error!void {
+ const rc = linux.pidfd_send_signal(self.fd, sig, null, 0);
+ if (linux.errno(rc) != .SUCCESS) return classify(linux.errno(rc));
+ }
+
+ pub fn alive(self: Handle) bool {
+ self.signal(@enumFromInt(0)) catch return false;
+ return true;
+ }
+
+ /// A nonblocking check of `fd`: has the process exited.
+ pub fn exited(self: Handle) bool {
+ var fds = [_]linux.pollfd{.{ .fd = self.fd, .events = linux.POLL.IN, .revents = 0 }};
+ return linux.errno(linux.poll(&fds, 1, 0)) == .SUCCESS and fds[0].revents != 0;
+ }
+
+ /// The pid of the process this handle is on: null once it has exited and
+ /// been reaped, even if the number was reused since. An unreaped zombie
+ /// still has its pid (see `exited`). Unavailable when the system cannot say.
+ pub fn pid(self: Handle) error{Unavailable}!?Pid {
+ var path: [64]u8 = undefined;
+ const name = std.fmt.bufPrintSentinel(&path, "/proc/self/fdinfo/{d}", .{self.fd}, 0) catch unreachable;
+ const opened = linux.openat(linux.AT.FDCWD, name.ptr, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NOFOLLOW = true }, 0);
+ if (linux.errno(opened) != .SUCCESS) return error.Unavailable;
+ const info_fd: i32 = @intCast(opened);
+ defer _ = linux.close(info_fd);
+ var buf: [4096]u8 = undefined;
+ var len: usize = 0;
+ while (len < buf.len) {
+ const rc = linux.read(info_fd, buf[len..].ptr, buf.len - len);
+ switch (linux.errno(rc)) {
+ .SUCCESS => {},
+ .INTR => continue,
+ else => return error.Unavailable,
+ }
+ if (rc == 0) break;
+ len += rc;
+ } else return error.Unavailable;
+ var lines = std.mem.splitScalar(u8, buf[0..len], '\n');
+ while (lines.next()) |line| {
+ if (!std.mem.startsWith(u8, line, "Pid:")) continue;
+ const value = std.fmt.parseInt(Pid, std.mem.trim(u8, line["Pid:".len..], " \t"), 10) catch return error.Unavailable;
+ return if (value < 0) null else value;
+ }
+ return null;
+ }
+};
+
+/// Collects the wait status of a child that has exited (or null: still
+/// running, or somebody else reaped it). Never blocks.
+pub fn reap(pid: Pid) ?u32 {
+ var status: u32 = 0;
+ while (true) {
+ const rc = linux.wait4(pid, @ptrCast(&status), linux.W.NOHANG, null);
+ switch (linux.errno(rc)) {
+ .INTR => continue,
+ .SUCCESS => return if (rc == pid) status else null,
+ else => return null,
+ }
+ }
+}
+
+/// Whether a process with this pid exists right now. Racy by nature: the pid
+/// may be another process's by the time it matters; prefer a `Handle`.
+pub fn exists(pid: Pid) bool {
+ return linux.errno(linux.kill(pid, @enumFromInt(0))) == .SUCCESS;
+}
+
+/// Signals every member of the process group `pgid`, a leader's own pid.
+pub fn signalGroup(pgid: Pid, sig: Signal) void {
+ _ = linux.kill(-pgid, sig);
+}
+
+/// 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.
+pub const Set = struct {
+ const Entry = struct { pid: Pid, handle: Handle };
+ pub const Exit = struct { pid: Pid, status: ?u32 };
+
+ /// Readable while `next` has an exit to report; -1 until the first `add`.
+ fd: i32 = -1,
+ entries: std.ArrayList(Entry) = .empty,
+
+ pub fn add(self: *Set, allocator: std.mem.Allocator, pid: Pid) !void {
+ try self.entries.ensureUnusedCapacity(allocator, 1);
+ if (self.fd < 0) {
+ const rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
+ if (linux.errno(rc) != .SUCCESS) return error.Failed;
+ self.fd = @intCast(rc);
+ }
+ const handle = try Handle.open(pid);
+ errdefer handle.close();
+ var event: linux.epoll_event = .{ .events = linux.EPOLL.IN, .data = .{ .fd = handle.fd } };
+ if (linux.errno(linux.epoll_ctl(self.fd, linux.EPOLL.CTL_ADD, handle.fd, &event)) != .SUCCESS) return error.Failed;
+ self.entries.appendAssumeCapacity(.{ .pid = pid, .handle = handle });
+ }
+
+ /// The next child that exited, reaped, or null when none has.
+ pub fn next(self: *Set) ?Exit {
+ if (self.fd < 0) return null;
+ var events: [1]linux.epoll_event = undefined;
+ const rc = linux.epoll_wait(self.fd, &events, 1, 0);
+ if (linux.errno(rc) != .SUCCESS or rc == 0) return null;
+ for (self.entries.items, 0..) |entry, i| {
+ if (entry.handle.fd != events[0].data.fd) continue;
+ _ = linux.epoll_ctl(self.fd, linux.EPOLL.CTL_DEL, entry.handle.fd, null);
+ entry.handle.close();
+ _ = self.entries.swapRemove(i);
+ return .{ .pid = entry.pid, .status = reap(entry.pid) };
+ }
+ unreachable;
+ }
+
+ pub fn signalAll(self: *Set, sig: Signal) void {
+ for (self.entries.items) |entry| entry.handle.signal(sig) catch {};
+ }
+
+ pub fn deinit(self: *Set, allocator: std.mem.Allocator) void {
+ while (self.next() != null) {}
+ for (self.entries.items) |entry| entry.handle.close();
+ self.entries.deinit(allocator);
+ if (self.fd >= 0) _ = linux.close(self.fd);
+ self.* = .{};
+ }
+};
+
+fn waitReadable(fd: i32, timeout_ms: i32) bool {
+ var fds = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.IN, .revents = 0 }};
+ return linux.errno(linux.poll(&fds, 1, timeout_ms)) == .SUCCESS and fds[0].revents != 0;
+}
+
+test "a handle follows one process through signal, exit and reap" {
+ const io = std.testing.io;
+ var child = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ const pid = child.id.?;
+ const handle = try Handle.open(pid);
+ defer handle.close();
+ try std.testing.expect(handle.alive());
+ try std.testing.expect(!handle.exited());
+ try std.testing.expectEqual(@as(?Pid, pid), try handle.pid());
+ try std.testing.expectEqual(@as(?u32, null), reap(pid));
+
+ try handle.signal(.TERM);
+ try std.testing.expect(waitReadable(handle.fd, 5000));
+ try std.testing.expect(handle.exited());
+ // The zombie keeps its pid until it is reaped; then the handle names nobody.
+ try std.testing.expectEqual(@as(?Pid, pid), try handle.pid());
+ const status = reap(pid).?;
+ try std.testing.expect(linux.W.IFSIGNALED(status) and linux.W.TERMSIG(status) == .TERM);
+ try std.testing.expectEqual(@as(?u32, null), reap(pid));
+ try std.testing.expectEqual(@as(?Pid, null), try handle.pid());
+ try std.testing.expectError(error.NoSuchProcess, handle.signal(.TERM));
+ child.id = null;
+}
+
+test "a handle cannot be opened on a process that does not exist" {
+ try std.testing.expectError(error.NoSuchProcess, Handle.open(std.math.maxInt(Pid)));
+}
+
+test "a set reports each exit once with its status and signals the rest" {
+ const io = std.testing.io;
+ var quick = try std.process.spawn(io, .{ .argv = &.{ "/bin/sh", "-c", "exit 3" } });
+ var slow = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ var set: Set = .{};
+ defer set.deinit(std.testing.allocator);
+ try set.add(std.testing.allocator, quick.id.?);
+ try set.add(std.testing.allocator, slow.id.?);
+ try std.testing.expect(waitReadable(set.fd, 5000));
+ const first = set.next().?;
+ try std.testing.expectEqual(quick.id.?, first.pid);
+ try std.testing.expectEqual(@as(u8, 3), linux.W.EXITSTATUS(first.status.?));
+ try std.testing.expect(set.next() == null);
+ set.signalAll(.KILL);
+ try std.testing.expect(waitReadable(set.fd, 5000));
+ const second = set.next().?;
+ try std.testing.expectEqual(slow.id.?, second.pid);
+ try std.testing.expect(linux.W.IFSIGNALED(second.status.?));
+ try std.testing.expectEqual(@as(usize, 0), set.entries.items.len);
+ quick.id = null;
+ slow.id = null;
+}
diff --git a/src/platform/exe.zig b/src/platform/exe.zig
index ba7d0d7..57a935d 100644
--- a/src/platform/exe.zig
+++ b/src/platform/exe.zig
@@ -1,18 +1,39 @@
//! The running program's own executable, for launching its siblings
//! (`rediwm-files`, `rediwm-pdf`, the Files terminal helper) and itself.
-//! Linux reads `/proc/self/exe`; `self_exe.h` is the C side.
+//! Linux reads `/proc/self/exe`, FreeBSD asks `kern.proc.pathname`;
+//! `self_exe.h` is the C side.
const std = @import("std");
+const builtin = @import("builtin");
const linux = std.os.linux;
+comptime {
+ if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
+ @compileError("platform.exe is not ported to this OS yet (docs/plans/freebsd.md, phase 1)");
+}
+
/// Room for any path the callers hand to `std.process.spawn`.
pub const max_path = 4096;
/// The absolute path of the running executable, in `buf`. Null when the link
/// cannot be read or the path does not fit.
pub fn path(buf: []u8) ?[]const u8 {
- const rc = linux.readlink("/proc/self/exe", buf.ptr, buf.len);
- if (linux.errno(rc) != .SUCCESS or rc == 0 or rc >= buf.len) return null;
- return buf[0..rc];
+ switch (builtin.os.tag) {
+ .linux => {
+ const rc = linux.readlink("/proc/self/exe", buf.ptr, buf.len);
+ if (linux.errno(rc) != .SUCCESS or rc == 0 or rc >= buf.len) return null;
+ return buf[0..rc];
+ },
+ .freebsd => {
+ // CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, this process (sys/sysctl.h).
+ const mib = [4]c_int{ 1, 14, 12, -1 };
+ var len: usize = buf.len;
+ if (std.c.sysctl(&mib, 4, buf.ptr, &len, null, 0) != 0) return null;
+ // The length counts the terminating NUL.
+ if (len < 2 or buf[len - 1] != 0) return null;
+ return buf[0 .. len - 1];
+ },
+ else => unreachable,
+ }
}
/// `<directory of this executable>/<name>`, NUL-terminated in `buf`. Null
@@ -27,13 +48,29 @@ pub fn sibling(buf: []u8, name: []const u8) ?[:0]const u8 {
/// spawner looks up on `PATH`.
pub fn siblingOrName(buf: []u8, name: []const u8) []const u8 {
const found = sibling(buf, name) orelse return name;
- return if (linux.errno(linux.access(found.ptr, std.posix.X_OK)) == .SUCCESS) found else name;
+ const accessible = switch (builtin.os.tag) {
+ .linux => linux.errno(linux.access(found.ptr, std.posix.X_OK)) == .SUCCESS,
+ .freebsd => std.c.access(found.ptr, std.posix.X_OK) == 0,
+ else => unreachable,
+ };
+ return if (accessible) found else name;
}
/// Replaces this process with a fresh copy of the same program image. Returns
/// only when the exec failed; callable between fork and exec (no allocation).
pub fn execSelf(argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) void {
- _ = linux.execve("/proc/self/exe", argv, envp);
+ switch (builtin.os.tag) {
+ .linux => _ = linux.execve("/proc/self/exe", argv, envp),
+ .freebsd => {
+ // By path: a program replaced on disk since it started runs as the
+ // new image (a descriptor kept from startup would run the old one).
+ var buf: [max_path]u8 = undefined;
+ const found = path(buf[0 .. max_path - 1]) orelse return;
+ buf[found.len] = 0;
+ _ = std.c.execve(@ptrCast(&buf), argv, envp);
+ },
+ else => unreachable,
+ }
}
test "own path is absolute and siblings sit beside it" {
diff --git a/src/platform/fs.zig b/src/platform/fs.zig
new file mode 100644
index 0000000..b1bc10f
--- /dev/null
+++ b/src/platform/fs.zig
@@ -0,0 +1,236 @@
+//! File operations that differ between systems. Linux has `renameat2`;
+//! FreeBSD has no rename that refuses to replace.
+const std = @import("std");
+const builtin = @import("builtin");
+const linux = std.os.linux;
+
+comptime {
+ if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
+ @compileError("platform.fs is not ported to this OS yet (docs/plans/freebsd.md, phase 1)");
+}
+
+/// What a path names, for the callers that compare identities or check an owner.
+pub const Stat = struct {
+ /// Device and inode: equal for the same file, whatever path reaches it.
+ dev: u64,
+ ino: u64,
+ uid: u32,
+ /// The type and permission bits, as `st_mode`.
+ mode: u32,
+};
+
+/// The identity, owner and mode of what `path` names (symbolic links
+/// followed), or null when it cannot be examined.
+pub fn stat(path: [*:0]const u8) ?Stat {
+ switch (builtin.os.tag) {
+ .linux => {
+ var info: linux.Statx = undefined;
+ const rc = linux.statx(linux.AT.FDCWD, path, 0, .{ .UID = true, .MODE = true, .INO = true }, &info);
+ if (linux.errno(rc) != .SUCCESS) return null;
+ return .{ .dev = @as(u64, info.dev_major) << 32 | info.dev_minor, .ino = info.ino, .uid = info.uid, .mode = info.mode };
+ },
+ .freebsd => {
+ var info: std.c.Stat = undefined;
+ if (std.c.fstatat(std.c.AT.FDCWD, path, &info, 0) != 0) return null;
+ return .{ .dev = @intCast(info.dev), .ino = @intCast(info.ino), .uid = info.uid, .mode = info.mode };
+ },
+ else => unreachable,
+ }
+}
+
+pub const AttributeError = error{
+ OutOfMemory,
+ /// The source's attributes changed while they were being read.
+ FileChanged,
+ MetadataFailed,
+};
+
+/// The largest attribute list or value copied.
+const max_attribute = 1024 * 1024;
+
+/// Copies the extended attributes (user ones, on FreeBSD) of one open file to
+/// another. A file system without them copies nothing and succeeds. The
+/// callers' libc is linked: these are libc functions, not raw syscalls.
+pub fn copyAttributes(allocator: std.mem.Allocator, source: c_int, destination: c_int) AttributeError!void {
+ switch (builtin.os.tag) {
+ .linux => try copyAttributesLinux(allocator, source, destination),
+ .freebsd => try copyAttributesFreebsd(allocator, source, destination),
+ else => unreachable,
+ }
+}
+
+fn copyAttributesLinux(a: std.mem.Allocator, source: c_int, destination: c_int) AttributeError!void {
+ const libc = struct {
+ extern "c" fn flistxattr(c_int, ?[*]u8, usize) isize;
+ extern "c" fn fgetxattr(c_int, [*:0]const u8, ?[*]u8, usize) isize;
+ extern "c" fn fsetxattr(c_int, [*:0]const u8, [*]const u8, usize, c_int) c_int;
+ };
+ const len = libc.flistxattr(source, null, 0);
+ if (len < 0) {
+ if (std.posix.errno(@as(c_int, -1)) == .OPNOTSUPP) return;
+ return error.MetadataFailed;
+ }
+ if (len == 0) return;
+ if (len > max_attribute) return error.MetadataFailed;
+ const names = try a.alloc(u8, @intCast(len));
+ defer a.free(names);
+ if (libc.flistxattr(source, names.ptr, names.len) != len) return error.FileChanged;
+ var offset: usize = 0;
+ while (offset < names.len) {
+ const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(names.ptr + offset)), 0);
+ const size = libc.fgetxattr(source, name, null, 0);
+ if (size < 0 or size > max_attribute) return error.MetadataFailed;
+ const value = try a.alloc(u8, @intCast(size));
+ defer a.free(value);
+ if (libc.fgetxattr(source, name, value.ptr, value.len) != size or libc.fsetxattr(destination, name, value.ptr, value.len, 0) != 0) return error.MetadataFailed;
+ offset += name.len + 1;
+ }
+}
+
+/// FreeBSD lists a file's user attributes as a run of length-prefixed names
+/// with no terminator and no namespace prefix.
+fn copyAttributesFreebsd(a: std.mem.Allocator, source: c_int, destination: c_int) AttributeError!void {
+ const libc = struct {
+ extern "c" fn extattr_list_fd(c_int, c_int, ?[*]u8, usize) isize;
+ extern "c" fn extattr_get_fd(c_int, c_int, [*:0]const u8, ?[*]u8, usize) isize;
+ extern "c" fn extattr_set_fd(c_int, c_int, [*:0]const u8, [*]const u8, usize) isize;
+ };
+ // EXTATTR_NAMESPACE_USER (sys/extattr.h); the system namespace needs root.
+ const user = 1;
+ const len = libc.extattr_list_fd(source, user, null, 0);
+ if (len < 0) {
+ if (std.posix.errno(@as(c_int, -1)) == .OPNOTSUPP) return;
+ return error.MetadataFailed;
+ }
+ if (len == 0) return;
+ if (len > max_attribute) return error.MetadataFailed;
+ const names = try a.alloc(u8, @intCast(len));
+ defer a.free(names);
+ if (libc.extattr_list_fd(source, user, names.ptr, names.len) != len) return error.FileChanged;
+ var offset: usize = 0;
+ while (offset < names.len) {
+ const name_len = names[offset];
+ offset += 1;
+ if (name_len == 0 or name_len > names.len - offset) return error.MetadataFailed;
+ var name: [256:0]u8 = undefined;
+ @memcpy(name[0..name_len], names[offset..][0..name_len]);
+ name[name_len] = 0;
+ offset += name_len;
+ const size = libc.extattr_get_fd(source, user, &name, null, 0);
+ if (size < 0 or size > max_attribute) return error.MetadataFailed;
+ const value = try a.alloc(u8, @intCast(size));
+ defer a.free(value);
+ if (libc.extattr_get_fd(source, user, &name, value.ptr, value.len) != size) return error.MetadataFailed;
+ if (libc.extattr_set_fd(destination, user, &name, value.ptr, value.len) < 0) return error.MetadataFailed;
+ }
+}
+
+pub const RenameError = error{
+ /// `to` exists.
+ PathAlreadyExists,
+ AccessDenied,
+ /// `from` and `to` are on different file systems.
+ CrossDevice,
+ Failed,
+};
+
+fn classify(err: std.posix.E) RenameError {
+ return switch (err) {
+ .EXIST => error.PathAlreadyExists,
+ .ACCES => error.AccessDenied,
+ .XDEV => error.CrossDevice,
+ else => error.Failed,
+ };
+}
+
+/// Renames `from` to `to` unless `to` exists, in which case nothing changes
+/// and the error is `PathAlreadyExists`. Atomic on Linux. FreeBSD links the
+/// new name and then removes the old one, so a failure part way leaves the
+/// old name; a directory cannot be hard-linked and falls back to a check and
+/// `rename`, which a racing creator of `to` can beat.
+pub fn renameNoReplace(from: [*:0]const u8, to: [*:0]const u8) RenameError!void {
+ switch (builtin.os.tag) {
+ .linux => {
+ // Through libc when it is linked, so a test's LD_PRELOAD fault hook sees the call
+ // (tests/screenshot_save_hook.c); raw in this module's own libc-free tests.
+ if (builtin.link_libc) {
+ const libc = struct {
+ extern "c" fn renameat2(c_int, [*:0]const u8, c_int, [*:0]const u8, c_uint) c_int;
+ };
+ const rename_noreplace = 1;
+ if (libc.renameat2(linux.AT.FDCWD, from, linux.AT.FDCWD, to, rename_noreplace) != 0)
+ return classify(std.posix.errno(@as(c_int, -1)));
+ return;
+ }
+ const rc = linux.renameat2(linux.AT.FDCWD, from, linux.AT.FDCWD, to, .{ .NOREPLACE = true });
+ if (linux.errno(rc) != .SUCCESS) return classify(linux.errno(rc));
+ },
+ .freebsd => {
+ const c = std.c;
+ if (c.linkat(c.AT.FDCWD, from, c.AT.FDCWD, to, 0) == 0) {
+ if (c.unlink(from) == 0) return;
+ const failure = std.posix.errno(@as(c_int, -1));
+ _ = c.unlink(to);
+ return classify(failure);
+ }
+ const failure = std.posix.errno(@as(c_int, -1));
+ if (failure != .PERM) return classify(failure);
+ // EPERM: a directory. Look first, then rename.
+ var existing: c.Stat = undefined;
+ if (c.fstatat(c.AT.FDCWD, to, &existing, c.AT.SYMLINK_NOFOLLOW) == 0) return error.PathAlreadyExists;
+ if (c.rename(from, to) != 0) return classify(std.posix.errno(@as(c_int, -1)));
+ },
+ else => unreachable,
+ }
+}
+
+test "stat names a directory's owner and mode, and the same file twice" {
+ const t = std.testing;
+ var tmp = t.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator);
+ defer t.allocator.free(root);
+ const first = stat(root).?;
+ try t.expectEqual(std.posix.system.getuid(), first.uid);
+ try t.expect(first.mode & std.posix.S.IFMT == std.posix.S.IFDIR);
+ try t.expect(first.ino != 0);
+ const dotted = try std.fmt.allocPrintSentinel(t.allocator, "{s}/.", .{root}, 0);
+ defer t.allocator.free(dotted);
+ try t.expectEqual(first, stat(dotted).?);
+ try t.expect(stat("/rediwm-no-such-path") == null);
+}
+
+test "rename without replacing moves a file, and refuses an existing target" {
+ const t = std.testing;
+ var tmp = t.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(t.io, .{ .sub_path = "a", .data = "a" });
+ try tmp.dir.writeFile(t.io, .{ .sub_path = "b", .data = "b" });
+ const root = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator);
+ defer t.allocator.free(root);
+ const a = try std.fmt.allocPrintSentinel(t.allocator, "{s}/a", .{root}, 0);
+ defer t.allocator.free(a);
+ const b = try std.fmt.allocPrintSentinel(t.allocator, "{s}/b", .{root}, 0);
+ defer t.allocator.free(b);
+ const c_path = try std.fmt.allocPrintSentinel(t.allocator, "{s}/c", .{root}, 0);
+ defer t.allocator.free(c_path);
+
+ try t.expectError(error.PathAlreadyExists, renameNoReplace(a, b));
+ var kept: [1]u8 = undefined;
+ try t.expectEqualStrings("a", try tmp.dir.readFile(t.io, "a", &kept));
+ try t.expectEqualStrings("b", try tmp.dir.readFile(t.io, "b", &kept));
+
+ try renameNoReplace(a, c_path);
+ try t.expectError(error.FileNotFound, tmp.dir.access(t.io, "a", .{}));
+ try t.expectEqualStrings("a", try tmp.dir.readFile(t.io, "c", &kept));
+
+ try tmp.dir.createDir(t.io, "d", .default_dir);
+ const d = try std.fmt.allocPrintSentinel(t.allocator, "{s}/d", .{root}, 0);
+ defer t.allocator.free(d);
+ const e = try std.fmt.allocPrintSentinel(t.allocator, "{s}/e", .{root}, 0);
+ defer t.allocator.free(e);
+ try renameNoReplace(d, e);
+ try tmp.dir.access(t.io, "e", .{});
+ try tmp.dir.createDir(t.io, "d", .default_dir);
+ try t.expectError(error.PathAlreadyExists, renameNoReplace(d, e));
+}
diff --git a/src/platform/mod.zig b/src/platform/mod.zig
index 4625ba8..52fe7f5 100644
--- a/src/platform/mod.zig
+++ b/src/platform/mod.zig
@@ -1,12 +1,14 @@
//! Everything that differs between operating systems, behind one interface:
//! child processes, file-change notification, the program's own path, where
//! the system's helper programs live, who is on the other end of a unix socket,
+//! renaming without replacing,
//! 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 fs = @import("fs.zig");
pub const peer = @import("peer.zig");
pub const process = @import("process.zig");
pub const wake = @import("wake.zig");
@@ -14,14 +16,17 @@ pub const power_supply = @import("power_supply.zig");
pub const charge_limit = @import("charge_limit.zig");
pub const watch = @import("watch.zig");
pub const seccomp = @import("seccomp.zig");
+pub const system = @import("system.zig");
pub const tool = @import("tool.zig");
test {
_ = child;
_ = exe;
+ _ = fs;
_ = peer;
_ = process;
_ = wake;
+ _ = system;
_ = tool;
_ = watch;
_ = @import("seccomp_tests.zig");
diff --git a/src/platform/peer.h b/src/platform/peer.h
index 51f4cee..7e8550b 100644
--- a/src/platform/peer.h
+++ b/src/platform/peer.h
@@ -1,13 +1,12 @@
/* 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). */
+ * compilers define it themselves). FreeBSD reads LOCAL_PEERCRED. */
#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
+#if defined(__linux__)
+
#ifndef _GNU_SOURCE
#error "platform/peer.h needs _GNU_SOURCE defined before any system header"
#endif
@@ -28,4 +27,30 @@ static inline int rediwm_peer_credentials(int fd, uid_t *uid, pid_t *pid) {
return 0;
}
+#elif defined(__FreeBSD__)
+
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/ucred.h>
+#include <sys/un.h>
+
+/* As on Linux. The pid comes from `cr_pid`, which a kernel that does not fill
+ * it leaves 0: a caller that asks for the pid then refuses the peer. */
+static inline int rediwm_peer_credentials(int fd, uid_t *uid, pid_t *pid) {
+ struct xucred cred;
+ socklen_t size = sizeof cred;
+ if (getsockopt(fd, SOL_LOCAL, LOCAL_PEERCRED, &cred, &size) != 0 || size != sizeof cred ||
+ cred.cr_version != XUCRED_VERSION)
+ return -1;
+ if (pid && cred.cr_pid <= 0) return -1;
+ if (uid) *uid = cred.cr_uid;
+ if (pid) *pid = cred.cr_pid;
+ return 0;
+}
+
+#else
+#error "platform/peer.h is not ported to this OS yet (docs/plans/freebsd.md, P.9)"
+#endif
+
#endif
diff --git a/src/platform/peer.zig b/src/platform/peer.zig
index 3be376e..502db1d 100644
--- a/src/platform/peer.zig
+++ b/src/platform/peer.zig
@@ -1,5 +1,6 @@
//! 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++.
+//! SO_PEERCRED, FreeBSD LOCAL_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`).
@@ -10,7 +11,7 @@ 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)
+ if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
@compileError("platform.peer is not ported to this OS yet (docs/plans/freebsd.md, P.9)");
}
@@ -26,36 +27,66 @@ const Ucred = extern struct {
gid: std.posix.gid_t,
};
+/// FreeBSD's `struct xucred` (`sys/ucred.h`): the first group is the effective
+/// gid, and `cr_pid` shares its slot with an unused pointer.
+const Xucred = extern struct {
+ cr_version: c_uint,
+ cr_uid: std.posix.uid_t,
+ cr_ngroups: c_short,
+ cr_groups: [16]std.posix.gid_t,
+ cr_pid: extern union { unused: ?*anyopaque, pid: std.posix.pid_t },
+
+ const version = 0;
+ const sol_local = 0;
+ const local_peercred = 1;
+};
+
/// 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.
+/// connected, or no process id): 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 };
+ switch (builtin.os.tag) {
+ .linux => {
+ 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 };
+ },
+ .freebsd => {
+ var cred: Xucred = undefined;
+ var len: std.c.socklen_t = @sizeOf(Xucred);
+ if (std.c.getsockopt(fd, Xucred.sol_local, Xucred.local_peercred, &cred, &len) != 0) return null;
+ if (len != @sizeOf(Xucred) or cred.cr_version != Xucred.version) return null;
+ // A kernel that does not fill cr_pid leaves it 0: no answer.
+ if (cred.cr_pid.pid <= 0) return null;
+ return .{ .uid = cred.cr_uid, .pid = cred.cr_pid.pid };
+ },
+ else => unreachable,
+ }
}
test "both ends of a socketpair name this process" {
+ const sys = std.posix.system;
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)));
+ try std.testing.expectEqual(std.posix.E.SUCCESS, std.posix.errno(sys.socketpair(std.posix.AF.UNIX, std.posix.SOCK.STREAM | std.posix.SOCK.CLOEXEC, 0, &fds)));
defer for (fds) |fd| {
- _ = linux.close(fd);
+ _ = sys.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);
+ try std.testing.expectEqual(sys.getuid(), peer.uid);
+ try std.testing.expectEqual(sys.getpid(), peer.pid);
}
}
test "a descriptor that is not a connected socket has no peer" {
+ const sys = std.posix.system;
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 })));
+ try std.testing.expectEqual(std.posix.E.SUCCESS, std.posix.errno(sys.pipe(&fds)));
defer for (fds) |fd| {
- _ = linux.close(fd);
+ _ = sys.close(fd);
};
try std.testing.expect(of(fds[0]) == null);
}
diff --git a/src/platform/process.h b/src/platform/process.h
index dae7ec5..b691674 100644
--- a/src/platform/process.h
+++ b/src/platform/process.h
@@ -1,11 +1,13 @@
/* Process attributes that differ between systems, for the C code that cannot
- * import platform/process.zig; the same contract. Linux uses prctl. */
+ * import platform/process.zig; the same contract. Linux uses prctl, FreeBSD
+ * procctl. */
#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 <stddef.h>
+#include <sys/mman.h>
+
+#if defined(__linux__)
#include <sys/prctl.h>
@@ -26,4 +28,48 @@ static inline void rediwm_process_set_name(const char *name) {
(void)prctl(PR_SET_NAME, name, 0, 0, 0);
}
+/* Keeps [p, p + n) out of core dumps (a password sits there). Returns 0, or -1;
+ * MADV_DONTDUMP needs _GNU_SOURCE, and without it this fails, never silently
+ * succeeds. */
+static inline int rediwm_process_no_dump_range(void *p, size_t n) {
+#ifdef MADV_DONTDUMP
+ return madvise(p, n, MADV_DONTDUMP);
+#else
+ (void)p; (void)n;
+ return -1;
+#endif
+}
+
+#elif defined(__FreeBSD__)
+
+#include <sys/types.h>
+#include <sys/procctl.h>
+#include <pthread.h>
+#include <pthread_np.h>
+#include <unistd.h>
+
+static inline int rediwm_process_procctl(int command, int value) {
+ return procctl(P_PID, getpid(), command, &value);
+}
+
+static inline int rediwm_process_deny_dumps(void) {
+ return rediwm_process_procctl(PROC_TRACE_CTL, PROC_TRACE_CTL_DISABLE);
+}
+
+static inline int rediwm_process_no_new_privileges(void) {
+ return rediwm_process_procctl(PROC_NO_NEW_PRIVS_CTL, PROC_NO_NEW_PRIVS_ENABLE);
+}
+
+static inline void rediwm_process_set_name(const char *name) {
+ pthread_set_name_np(pthread_self(), name);
+}
+
+static inline int rediwm_process_no_dump_range(void *p, size_t n) {
+ return madvise(p, n, MADV_NOCORE);
+}
+
+#else
+#error "platform/process.h is not ported to this OS yet (docs/plans/freebsd.md, P.4)"
+#endif
+
#endif
diff --git a/src/platform/process.zig b/src/platform/process.zig
index e1988f7..94bbc2d 100644
--- a/src/platform/process.zig
+++ b/src/platform/process.zig
@@ -1,6 +1,6 @@
//! 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.
+//! uses prctl, FreeBSD procctl. `process.h` is the same for C.
const std = @import("std");
const builtin = @import("builtin");
const linux = std.os.linux;
@@ -9,12 +9,76 @@ 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)
+ if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
@compileError("platform.process is not ported to this OS yet (docs/plans/freebsd.md, P.4)");
}
+/// FreeBSD's procctl(2): the commands and values of `sys/procctl.h`.
+const bsd = struct {
+ extern "c" fn procctl(idtype: c_int, id: i64, cmd: c_int, data: ?*anyopaque) c_int;
+ const P_PID: c_int = 0;
+ const PROC_REAP_ACQUIRE = 2;
+ const PROC_REAP_RELEASE = 3;
+ const PROC_REAP_STATUS = 4;
+ const PROC_TRACE_CTL = 7;
+ const PROC_TRACE_STATUS = 8;
+ const PROC_PDEATHSIG_CTL = 11;
+ const PROC_PDEATHSIG_STATUS = 12;
+ const PROC_NO_NEW_PRIVS_CTL = 19;
+ const PROC_NO_NEW_PRIVS_STATUS = 20;
+ const TRACE_CTL_ENABLE: c_int = 1;
+ const TRACE_CTL_DISABLE: c_int = 2;
+ const NO_NEW_PRIVS_ENABLE: c_int = 1;
+ const REAPER_STATUS_OWNED = 1;
+
+ const ReaperStatus = extern struct {
+ rs_flags: c_uint,
+ rs_children: c_uint,
+ rs_descendants: c_uint,
+ rs_reaper: i32,
+ rs_pid: i32,
+ rs_pad0: [15]c_uint,
+ };
+
+ /// procctl on this process.
+ fn self(cmd: c_int, data: ?*anyopaque) Error!void {
+ if (procctl(P_PID, std.c.getpid(), cmd, data) != 0) return error.Failed;
+ }
+};
+
pub const Error = error{Failed};
+/// A write to a closed pipe or socket then fails with EPIPE instead of ending
+/// the program with SIGPIPE. Not reversible by a caller that wants the default.
+pub fn ignoreBrokenPipes() void {
+ setHandler(.PIPE, std.posix.SIG.IGN);
+}
+
+/// Makes the calling thread nicer (`nice` 0..19, higher yields more) without
+/// touching the others. Linux only: FreeBSD's `setpriority` takes a process,
+/// so there the call changes nothing.
+pub fn lowerThreadPriority(nice: c_int) void {
+ if (builtin.os.tag != .linux) return;
+ const libc = struct {
+ extern "c" fn setpriority(which: c_int, who: c_uint, prio: c_int) c_int;
+ };
+ _ = libc.setpriority(0, @intCast(linux.gettid()), nice);
+}
+
+/// Puts `sig` back to its default action.
+pub fn defaultSignal(sig: child.Signal) void {
+ setHandler(sig, std.posix.SIG.DFL);
+}
+
+fn setHandler(sig: child.Signal, handler: anytype) void {
+ const action: std.posix.Sigaction = .{
+ .handler = .{ .handler = handler },
+ .mask = std.posix.sigemptyset(),
+ .flags = 0,
+ };
+ std.posix.sigaction(sig, &action, null);
+}
+
fn check(rc: usize) Error!void {
if (linux.errno(rc) != .SUCCESS) return error.Failed;
}
@@ -22,30 +86,66 @@ fn check(rc: usize) Error!void {
/// 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);
+ switch (builtin.os.tag) {
+ .linux => _ = linux.prctl(@intFromEnum(linux.PR.SET_PDEATHSIG), @intFromEnum(sig), 0, 0, 0),
+ .freebsd => {
+ var number: c_int = @intCast(@intFromEnum(sig));
+ bsd.self(bsd.PROC_PDEATHSIG_CTL, &number) catch {};
+ },
+ else => unreachable,
+ }
}
/// 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).
+/// Like Linux's dumpable flag it lasts for this program image: exec resets it.
pub fn denyDumps() Error!void {
- try check(linux.prctl(@intFromEnum(linux.PR.SET_DUMPABLE), 0, 0, 0, 0));
+ switch (builtin.os.tag) {
+ .linux => try check(linux.prctl(@intFromEnum(linux.PR.SET_DUMPABLE), 0, 0, 0, 0)),
+ .freebsd => {
+ var mode = bsd.TRACE_CTL_DISABLE;
+ try bsd.self(bsd.PROC_TRACE_CTL, &mode);
+ },
+ else => unreachable,
+ }
}
/// 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));
+ switch (builtin.os.tag) {
+ .linux => try check(linux.prctl(@intFromEnum(linux.PR.SET_NO_NEW_PRIVS), 1, 0, 0, 0)),
+ .freebsd => {
+ var mode = bsd.NO_NEW_PRIVS_ENABLE;
+ try bsd.self(bsd.PROC_NO_NEW_PRIVS_CTL, &mode);
+ },
+ else => unreachable,
+ }
}
/// 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;
+ switch (builtin.os.tag) {
+ .linux => {
+ var on: c_int = 0;
+ try check(linux.prctl(@intFromEnum(linux.PR.GET_CHILD_SUBREAPER), @intFromPtr(&on), 0, 0, 0));
+ return on != 0;
+ },
+ .freebsd => {
+ var status: bsd.ReaperStatus = std.mem.zeroes(bsd.ReaperStatus);
+ try bsd.self(bsd.PROC_REAP_STATUS, &status);
+ return status.rs_flags & bsd.REAPER_STATUS_OWNED != 0;
+ },
+ else => unreachable,
+ }
}
pub fn setChildSubreaper(on: bool) Error!void {
- try check(linux.prctl(@intFromEnum(linux.PR.SET_CHILD_SUBREAPER), @intFromBool(on), 0, 0, 0));
+ switch (builtin.os.tag) {
+ .linux => try check(linux.prctl(@intFromEnum(linux.PR.SET_CHILD_SUBREAPER), @intFromBool(on), 0, 0, 0)),
+ .freebsd => try bsd.self(if (on) bsd.PROC_REAP_ACQUIRE else bsd.PROC_REAP_RELEASE, null),
+ else => unreachable,
+ }
}
test "the subreaper setting is read, changed and restored" {
@@ -57,6 +157,23 @@ test "the subreaper setting is read, changed and restored" {
}
test "dumps are denied and the death signal is set, then both restored" {
+ if (builtin.os.tag == .freebsd) {
+ var status: c_int = 0;
+ try bsd.self(bsd.PROC_TRACE_STATUS, &status);
+ try std.testing.expect(status >= 0); // tracing allowed before
+ try denyDumps();
+ try bsd.self(bsd.PROC_TRACE_STATUS, &status);
+ try std.testing.expectEqual(@as(c_int, -1), status);
+ var enable = bsd.TRACE_CTL_ENABLE;
+ try bsd.self(bsd.PROC_TRACE_CTL, &enable);
+
+ dieWithParent(.TERM);
+ var signal: c_int = -1;
+ try bsd.self(bsd.PROC_PDEATHSIG_STATUS, &signal);
+ try std.testing.expectEqual(@as(c_int, @intCast(@intFromEnum(child.Signal.TERM))), signal);
+ dieWithParent(@enumFromInt(0));
+ return;
+ }
const dumpable = linux.prctl(@intFromEnum(linux.PR.GET_DUMPABLE), 0, 0, 0, 0);
try std.testing.expect(linux.errno(dumpable) == .SUCCESS);
try denyDumps();
diff --git a/src/platform/self_exe.h b/src/platform/self_exe.h
index 93c03c0..c21686b 100644
--- a/src/platform/self_exe.h
+++ b/src/platform/self_exe.h
@@ -1,20 +1,33 @@
/* The running program's own path, for the C and C++ code that cannot import
- * platform/exe.zig. Linux reads /proc/self/exe. */
+ * platform/exe.zig. Linux reads /proc/self/exe, FreeBSD kern.proc.pathname. */
#ifndef REDIWM_SELF_EXE_H
#define REDIWM_SELF_EXE_H
#include <stddef.h>
#include <sys/types.h>
#include <unistd.h>
+#if defined(__FreeBSD__)
+#include <sys/sysctl.h>
+#elif !defined(__linux__)
+#error "platform/self_exe.h is not ported to this OS yet (docs/plans/freebsd.md, phase 1)"
+#endif
/* Writes the NUL-terminated absolute path of the running executable into
* `buf`. Returns its length, or -1 when it cannot be read or does not fit. */
static inline ssize_t rediwm_self_exe(char *buf, size_t size) {
if (size < 2) return -1;
+#if defined(__FreeBSD__)
+ int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
+ size_t len = size;
+ /* The length counts the terminating NUL. */
+ if (sysctl(mib, 4, buf, &len, NULL, 0) != 0 || len < 2 || buf[len - 1] != '\0') return -1;
+ return (ssize_t)(len - 1);
+#else
ssize_t len = readlink("/proc/self/exe", buf, size - 1);
if (len <= 0) return -1;
buf[len] = '\0';
return len;
+#endif
}
#endif
diff --git a/src/platform/system.zig b/src/platform/system.zig
new file mode 100644
index 0000000..34aab86
--- /dev/null
+++ b/src/platform/system.zig
@@ -0,0 +1,17 @@
+//! Facts about the running system that differ between operating systems.
+const std = @import("std");
+const builtin = @import("builtin");
+
+/// Time since boot, suspended time included where the system counts it:
+/// Linux's CLOCK_BOOTTIME, FreeBSD's CLOCK_UPTIME.
+pub const boot_clock: std.posix.clockid_t = switch (builtin.os.tag) {
+ .linux => .BOOTTIME,
+ .freebsd => .UPTIME,
+ else => @compileError("platform.system is not ported to this OS yet (docs/plans/freebsd.md, phase 1)"),
+};
+
+test "the boot clock reads a time" {
+ var ts: std.posix.timespec = undefined;
+ try std.testing.expectEqual(std.posix.E.SUCCESS, std.posix.errno(std.posix.system.clock_gettime(boot_clock, &ts)));
+ try std.testing.expect(ts.sec > 0);
+}
diff --git a/src/platform/wake.zig b/src/platform/wake.zig
index f0d08df..7a6a80b 100644
--- a/src/platform/wake.zig
+++ b/src/platform/wake.zig
@@ -1,6 +1,6 @@
-//! 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.
+//! Descriptors that wake a poll loop from another thread. Both systems use
+//! 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;
@@ -8,32 +8,43 @@ 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)
+ if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
@compileError("platform.wake is not ported to this OS yet (docs/plans/freebsd.md, P.4)");
}
/// 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;
+ switch (builtin.os.tag) {
+ .linux => {
+ const rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
+ if (linux.errno(rc) != .SUCCESS) return null;
+ return @intCast(rc);
+ },
+ .freebsd => {
+ // EFD_NONBLOCK is O_NONBLOCK and EFD_CLOEXEC is O_CLOEXEC (sys/eventfd.h).
+ const fd = std.c.eventfd(0, 0x00000004 | 0x00100000);
+ return if (fd < 0) null else fd;
+ },
+ else => unreachable,
+ }
}
test "a wake descriptor turns readable when written and drains when read" {
+ const sys = std.posix.system;
const fd = create().?;
- defer _ = linux.close(fd);
+ defer _ = sys.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.expectEqual(@as(usize, 8), @as(usize, @intCast(sys.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(usize, 8), @as(usize, @intCast(sys.read(fd, std.mem.asBytes(&count), 8))));
try std.testing.expectEqual(@as(u64, 1), count);
try std.testing.expect(!readable(fd));
}
+
+fn readable(fd: std.posix.fd_t) bool {
+ var fds = [_]std.posix.pollfd{.{ .fd = fd, .events = std.posix.POLL.IN, .revents = 0 }};
+ return std.posix.errno(std.posix.system.poll(&fds, 1, 0)) == .SUCCESS and fds[0].revents != 0;
+}
diff --git a/src/platform/watch.zig b/src/platform/watch.zig
index e08627a..aad8b15 100644
--- a/src/platform/watch.zig
+++ b/src/platform/watch.zig
@@ -1,11 +1,101 @@
//! File-change notification for directories. A `Watcher` is one pollable fd
//! that turns readable while events are queued; hand `fd` to the Wayland
-//! loop or a `poll` and call `drain` when it fires. Linux backs it with
-//! inotify; events carry the entry name and neutral flags, so a backend
-//! without names can synthesize them by diffing the directory.
+//! loop or a `poll` and call `drain` when it fires. Linux and FreeBSD (15 and
+//! later, which have inotify in libc) back it with inotify; events carry the
+//! entry name and neutral flags, so a backend without names can synthesize
+//! them by diffing the directory.
const std = @import("std");
+const builtin = @import("builtin");
const linux = std.os.linux;
+comptime {
+ if (builtin.os.tag != .linux and builtin.os.tag != .freebsd)
+ @compileError("platform.watch is not ported to this OS yet (docs/plans/freebsd.md, phase 1)");
+}
+
+/// inotify's event mask and record, identical on both systems
+/// (`sys/inotify.h`).
+const IN = struct {
+ const MODIFY = 0x00000002;
+ const ATTRIB = 0x00000004;
+ const CLOSE_WRITE = 0x00000008;
+ const MOVED_FROM = 0x00000040;
+ const MOVED_TO = 0x00000080;
+ const CREATE = 0x00000100;
+ const DELETE = 0x00000200;
+ const DELETE_SELF = 0x00000400;
+ const MOVE_SELF = 0x00000800;
+ const UNMOUNT = 0x00002000;
+ const Q_OVERFLOW = 0x00004000;
+ const IGNORED = 0x00008000;
+ const ISDIR = 0x40000000;
+};
+
+const InotifyEvent = extern struct {
+ wd: i32,
+ mask: u32,
+ cookie: u32,
+ len: u32,
+};
+
+/// The system calls: raw syscalls on Linux, libc on FreeBSD, whose errno the
+/// raw Linux calls would not set.
+const sys = switch (builtin.os.tag) {
+ .linux => struct {
+ fn init() ?i32 {
+ const rc = linux.inotify_init1(linux.IN.NONBLOCK | linux.IN.CLOEXEC);
+ return if (linux.errno(rc) == .SUCCESS) @intCast(rc) else null;
+ }
+ fn close(fd: i32) void {
+ _ = linux.close(fd);
+ }
+ fn add(fd: i32, path: [*:0]const u8, m: u32) ?i32 {
+ const rc = linux.inotify_add_watch(fd, path, m);
+ return if (linux.errno(rc) == .SUCCESS) @intCast(rc) else null;
+ }
+ fn remove(fd: i32, watch: i32) void {
+ _ = linux.inotify_rm_watch(fd, watch);
+ }
+ /// Bytes read, or why not.
+ fn read(fd: i32, buf: []u8) union(enum) { bytes: usize, interrupted, empty, broken } {
+ const rc = linux.read(fd, buf.ptr, buf.len);
+ return switch (linux.errno(rc)) {
+ .SUCCESS => .{ .bytes = rc },
+ .INTR => .interrupted,
+ .AGAIN => .empty,
+ else => .broken,
+ };
+ }
+ },
+ .freebsd => struct {
+ // IN_NONBLOCK is O_NONBLOCK and IN_CLOEXEC is O_CLOEXEC (sys/inotify.h).
+ fn init() ?i32 {
+ const fd = std.c.inotify_init1(0x00000004 | 0x00100000);
+ return if (fd < 0) null else fd;
+ }
+ fn close(fd: i32) void {
+ _ = std.c.close(fd);
+ }
+ fn add(fd: i32, path: [*:0]const u8, m: u32) ?i32 {
+ const wd = std.c.inotify_add_watch(fd, path, m);
+ return if (wd < 0) null else wd;
+ }
+ fn remove(fd: i32, watch: i32) void {
+ _ = std.c.inotify_rm_watch(fd, watch);
+ }
+ fn read(fd: i32, buf: []u8) union(enum) { bytes: usize, interrupted, empty, broken } {
+ const rc = std.c.read(fd, buf.ptr, buf.len);
+ if (rc >= 0) return .{ .bytes = @intCast(rc) };
+ return switch (std.posix.errno(rc)) {
+ .INTR => .interrupted,
+ .AGAIN => .empty,
+ else => .broken,
+ };
+ }
+ },
+ else => unreachable,
+};
+
/// One watched directory. Negative means none.
pub const Watch = i32;
pub const none: Watch = -1;
@@ -66,13 +156,11 @@ pub const Watcher = struct {
fd: i32 = -1,
pub fn init() error{Unavailable}!Watcher {
- const rc = linux.inotify_init1(linux.IN.NONBLOCK | linux.IN.CLOEXEC);
- if (linux.errno(rc) != .SUCCESS) return error.Unavailable;
- return .{ .fd = @intCast(rc) };
+ return .{ .fd = sys.init() orelse return error.Unavailable };
}
pub fn deinit(self: *Watcher) void {
- if (self.fd >= 0) _ = linux.close(self.fd);
+ if (self.fd >= 0) sys.close(self.fd);
self.fd = -1;
}
@@ -82,9 +170,7 @@ pub const Watcher = struct {
pub fn add(self: Watcher, path: []const u8, interest: Flags) ?Watch {
var buf: [std.posix.PATH_MAX]u8 = undefined;
const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return null;
- const rc = linux.inotify_add_watch(self.fd, z.ptr, mask(interest));
- if (linux.errno(rc) != .SUCCESS) return null;
- return @intCast(rc);
+ return sys.add(self.fd, z.ptr, mask(interest));
}
/// `add`, falling back to the nearest existing parent directory, for
@@ -99,7 +185,7 @@ pub const Watcher = struct {
}
pub fn remove(self: Watcher, watch: Watch) void {
- _ = linux.inotify_rm_watch(self.fd, watch);
+ sys.remove(self.fd, watch);
}
/// Calls `onEvent(ctx, event)` for every queued event. `Broken` means the
@@ -111,22 +197,21 @@ pub const Watcher = struct {
/// `drain`, reading at most `max_batches` buffers (8 KiB, a few hundred
/// events each); the fd stays readable if more remain.
pub fn drainBounded(self: Watcher, ctx: anytype, comptime onEvent: fn (@TypeOf(ctx), Event) void, max_batches: usize) error{Broken}!void {
- var buf: [8192]u8 align(@alignOf(linux.inotify_event)) = undefined;
+ var buf: [8192]u8 align(@alignOf(InotifyEvent)) = undefined;
var batches: usize = 0;
while (batches < max_batches) : (batches += 1) {
- const rc = linux.read(self.fd, &buf, buf.len);
- switch (linux.errno(rc)) {
- .SUCCESS => {},
- .INTR => continue,
- .AGAIN => return,
- else => return error.Broken,
- }
+ const rc = switch (sys.read(self.fd, &buf)) {
+ .bytes => |n| n,
+ .interrupted => continue,
+ .empty => return,
+ .broken => return error.Broken,
+ };
if (rc == 0) return error.Broken;
var off: usize = 0;
while (off < rc) {
- const body = off + @sizeOf(linux.inotify_event);
+ const body = off + @sizeOf(InotifyEvent);
if (body > rc) return error.Broken;
- const raw: *const linux.inotify_event = @ptrCast(@alignCast(&buf[off]));
+ const raw: *const InotifyEvent = @ptrCast(@alignCast(&buf[off]));
if (raw.len > rc - body) return error.Broken;
onEvent(ctx, .{
.watch = raw.wd,
@@ -151,30 +236,30 @@ pub const Watcher = struct {
};
fn mask(interest: Flags) u32 {
- var m: u32 = linux.IN.DELETE_SELF | linux.IN.MOVE_SELF;
- if (interest.created) m |= linux.IN.CREATE;
- if (interest.deleted) m |= linux.IN.DELETE;
- if (interest.modified) m |= linux.IN.MODIFY;
- if (interest.moved_from) m |= linux.IN.MOVED_FROM;
- if (interest.moved_to) m |= linux.IN.MOVED_TO;
- if (interest.written) m |= linux.IN.CLOSE_WRITE;
- if (interest.attrib) m |= linux.IN.ATTRIB;
+ var m: u32 = IN.DELETE_SELF | IN.MOVE_SELF;
+ if (interest.created) m |= IN.CREATE;
+ if (interest.deleted) m |= IN.DELETE;
+ if (interest.modified) m |= IN.MODIFY;
+ if (interest.moved_from) m |= IN.MOVED_FROM;
+ if (interest.moved_to) m |= IN.MOVED_TO;
+ if (interest.written) m |= IN.CLOSE_WRITE;
+ if (interest.attrib) m |= IN.ATTRIB;
return m;
}
fn flags(m: u32) Flags {
return .{
- .created = m & linux.IN.CREATE != 0,
- .deleted = m & linux.IN.DELETE != 0,
- .modified = m & linux.IN.MODIFY != 0,
- .moved_from = m & linux.IN.MOVED_FROM != 0,
- .moved_to = m & linux.IN.MOVED_TO != 0,
- .written = m & linux.IN.CLOSE_WRITE != 0,
- .attrib = m & linux.IN.ATTRIB != 0,
- .self_gone = m & (linux.IN.DELETE_SELF | linux.IN.MOVE_SELF | linux.IN.UNMOUNT) != 0,
- .dropped = m & linux.IN.IGNORED != 0,
- .overflow = m & linux.IN.Q_OVERFLOW != 0,
- .is_dir = m & linux.IN.ISDIR != 0,
+ .created = m & IN.CREATE != 0,
+ .deleted = m & IN.DELETE != 0,
+ .modified = m & IN.MODIFY != 0,
+ .moved_from = m & IN.MOVED_FROM != 0,
+ .moved_to = m & IN.MOVED_TO != 0,
+ .written = m & IN.CLOSE_WRITE != 0,
+ .attrib = m & IN.ATTRIB != 0,
+ .self_gone = m & (IN.DELETE_SELF | IN.MOVE_SELF | IN.UNMOUNT) != 0,
+ .dropped = m & IN.IGNORED != 0,
+ .overflow = m & IN.Q_OVERFLOW != 0,
+ .is_dir = m & IN.ISDIR != 0,
};
}
diff --git a/src/polkit/helper.zig b/src/polkit/helper.zig
index f4166d1..7cabfcd 100644
--- a/src/polkit/helper.zig
+++ b/src/polkit/helper.zig
@@ -65,7 +65,7 @@ pub const Helper = struct {
self.fd = c.socket(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_NONBLOCK | c.SOCK_CLOEXEC, 0);
if (self.fd < 0) return error.SocketFailed;
var spawned = false;
- if (c.connect(self.fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @sizeOf(@TypeOf(addr))) < 0) {
+ if (std.c.connect(self.fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) < 0) {
switch (std.posix.errno(@as(c_int, -1))) {
.INPROGRESS => self.connecting = true,
.NOENT, .CONNREFUSED => {
diff --git a/src/polkit/native.c b/src/polkit/native.c
index b961330..6b52376 100644
--- a/src/polkit/native.c
+++ b/src/polkit/native.c
@@ -13,6 +13,7 @@
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
+#include "../platform/process.h"
/* NSS ABI boundary only: no PAM, credential validation or privileged code. */
struct rediwm_polkit_account { uint32_t uid, gid; char user[256], name[256]; };
@@ -67,7 +68,7 @@ void *rediwm_polkit_secret_new(void) {
size_t n = (size_t)getpagesize();
void *p = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) return NULL;
- if (mlock(p, n) || madvise(p, n, MADV_DONTDUMP)) { munlock(p, n); munmap(p, n); return NULL; }
+ if (mlock(p, n) || rediwm_process_no_dump_range(p, n)) { munlock(p, n); munmap(p, n); return NULL; }
return p;
}
void rediwm_polkit_clear(void *p, size_t n) { explicit_bzero(p, n); }
diff --git a/src/power_menu.zig b/src/power_menu.zig
index c2e3056..09ea0a3 100644
--- a/src/power_menu.zig
+++ b/src/power_menu.zig
@@ -1,5 +1,6 @@
// Centered session-action cards with system uptime.
const std = @import("std");
+const platform = @import("platform");
const i18n = @import("i18n");
const glass = @import("glass.zig");
const wl = @import("wayland").server.wl;
@@ -296,7 +297,7 @@ pub const PowerMenu = struct {
fn updateUptime(menu: *PowerMenu) bool {
var ts: std.posix.timespec = undefined;
- if (std.posix.errno(std.posix.system.clock_gettime(std.posix.CLOCK.BOOTTIME, &ts)) != .SUCCESS) return false;
+ if (std.posix.errno(std.posix.system.clock_gettime(platform.system.boot_clock, &ts)) != .SUCCESS) return false;
const minutes = @divTrunc(@max(0, ts.sec), 60);
if (menu.uptime_minutes == minutes) return false;
menu.uptime_minutes = minutes;
diff --git a/src/printing/client.zig b/src/printing/client.zig
index d4d24c5..a89ea17 100644
--- a/src/printing/client.zig
+++ b/src/printing/client.zig
@@ -441,24 +441,27 @@ fn drain(fd: c_int) void {
_ = c.read(fd, &count, @sizeOf(u64));
}
fn ueventSocket() c_int {
+ // Printer hotplug arrives as kernel uevents on Linux; elsewhere only rescans find new printers.
+ if (comptime !@hasDecl(c, "NETLINK_KOBJECT_UEVENT")) return -1;
const fd = c.socket(c.AF_NETLINK, c.SOCK_DGRAM | c.SOCK_CLOEXEC | c.SOCK_NONBLOCK, c.NETLINK_KOBJECT_UEVENT);
if (fd < 0) return -1;
var addr = std.mem.zeroes(c.struct_sockaddr_nl);
addr.nl_family = c.AF_NETLINK;
addr.nl_groups = 1;
- if (c.bind(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @sizeOf(c.struct_sockaddr_nl)) != 0) {
+ if (std.c.bind(fd, @ptrCast(&addr), @sizeOf(c.struct_sockaddr_nl)) != 0) {
_ = c.close(fd);
return -1;
}
return fd;
}
fn drainUevents(fd: c_int) bool {
+ if (comptime !@hasDecl(c, "NETLINK_KOBJECT_UEVENT")) return false;
var changed = false;
for (0..256) |_| {
var bytes: [8192]u8 = undefined;
var sender: c.struct_sockaddr_nl = undefined;
- var len: c.socklen_t = @sizeOf(c.struct_sockaddr_nl);
- const n = c.recvfrom(fd, &bytes, bytes.len, 0, .{ .__sockaddr__ = @ptrCast(&sender) }, &len);
+ var len: std.c.socklen_t = @sizeOf(c.struct_sockaddr_nl);
+ const n = std.c.recvfrom(fd, &bytes, bytes.len, 0, @ptrCast(&sender), &len);
if (n <= 0) break;
if (sender.nl_pid != 0) continue;
var words = std.mem.splitScalar(u8, bytes[0..@intCast(n)], 0);
diff --git a/src/printing/direct.c b/src/printing/direct.c
index 6811eed..6b3fe07 100644
--- a/src/printing/direct.c
+++ b/src/printing/direct.c
@@ -6,6 +6,7 @@
#include <pthread.h>
#include <stdatomic.h>
#include <sys/eventfd.h>
+#include "../platform/process.h"
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
@@ -406,7 +407,7 @@ struct rediwm_cups *rediwm_cups_create(void) {
w->password = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (w->password == MAP_FAILED) { free(w); return NULL; }
if (mlock(w->password, 4096)) { munmap(w->password, 4096); free(w); return NULL; }
- madvise(w->password, 4096, MADV_DONTDUMP);
+ rediwm_process_no_dump_range(w->password, 4096);
w->fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (w->fd < 0) goto fail;
if (pthread_mutex_init(&w->mutex, NULL)) goto fail_fd;
diff --git a/src/printing/http.zig b/src/printing/http.zig
index 0e9e4d4..fd47814 100644
--- a/src/printing/http.zig
+++ b/src/printing/http.zig
@@ -175,7 +175,7 @@ pub fn sendNoWait(server: []const u8, resource: []const u8, body: []const u8) !v
var addr: c.struct_sockaddr_un = std.mem.zeroes(c.struct_sockaddr_un);
addr.sun_family = c.AF_UNIX;
@memcpy(addr.sun_path[0..socket.len], socket);
- if (c.connect(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1)) != 0) return error.ConnectionFailed;
+ if (std.c.connect(fd, @ptrCast(&addr), @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1)) != 0) return error.ConnectionFailed;
var packet: [2048]u8 = undefined;
const headers = std.fmt.bufPrint(&packet, "POST {s} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/ipp\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n", .{ resource, body.len }) catch return error.RequestTooLarge;
if (headers.len + body.len > packet.len) return error.RequestTooLarge;
@@ -204,7 +204,7 @@ fn connectUnix(socket: []const u8, cancel: c_int, deadline: i64) !c_int {
var addr: c.struct_sockaddr_un = std.mem.zeroes(c.struct_sockaddr_un);
addr.sun_family = c.AF_UNIX;
@memcpy(addr.sun_path[0..socket.len], socket);
- const result = c.connect(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1));
+ const result = std.c.connect(fd, @ptrCast(&addr), @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1));
if (result < 0) {
const e = std.posix.errno(result);
if (e == .NOENT or e == .CONNREFUSED) return error.CupsUnavailable;
@@ -274,11 +274,11 @@ fn connectTcp(io: ?std.Io, target: endpoint.Endpoint, cancel: c_int, deadline: i
const result = switch (address) {
.ip4 => |ip| blk: {
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)));
+ break :blk std.c.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr)));
},
.ip6 => |ip| blk: {
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)));
+ break :blk std.c.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr)));
},
};
if (result == 0) return fd;
@@ -356,17 +356,17 @@ test "remote loopback HTTP preserves authority, resource and body" {
try t.expect(listener >= 0);
defer _ = c.close(listener);
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), std.c.bind(listener, @ptrCast(&address), @sizeOf(@TypeOf(address))));
try t.expectEqual(@as(c_int, 0), c.listen(listener, 1));
- var length: c.socklen_t = @sizeOf(@TypeOf(address));
- try t.expectEqual(@as(c_int, 0), c.getsockname(listener, .{ .__sockaddr__ = @ptrCast(&address) }, &length));
+ var length: std.c.socklen_t = @sizeOf(@TypeOf(address));
+ try t.expectEqual(@as(c_int, 0), std.c.getsockname(listener, @ptrCast(&address), &length));
const Fixture = struct {
listener: c_int,
bytes: [4096]u8 = undefined,
count: usize = 0,
fn run(self: *@This()) void {
ready(self.listener, c.POLLIN, -1, nowMs() + 3000) catch return;
- const fd = c.accept(self.listener, .{ .__sockaddr__ = null }, null);
+ const fd = std.c.accept(self.listener, null, null);
if (fd < 0) return;
defer _ = c.close(fd);
while (self.count < self.bytes.len) {
diff --git a/src/screenshot/save.zig b/src/screenshot/save.zig
index 102bd26..f6b9ebf 100644
--- a/src/screenshot/save.zig
+++ b/src/screenshot/save.zig
@@ -1,6 +1,7 @@
//! Publish only complete PNGs: file browsers may inspect a path at IN_CREATE.
//! All I/O runs on the capture worker, never on the compositor event loop.
const std = @import("std");
+const platform = @import("platform");
const c = @import("c");
pub fn writePngFile(path: []const u8, bytes: []const u8) !void {
@@ -33,5 +34,5 @@ pub fn writePngFile(path: []const u8, bytes: []const u8) !void {
if (close_result != 0) return error.CloseFailed;
// NOREPLACE retains the IPC's no-overwrite guarantee, including symlinks
// and another writer winning the race after queueRequest checked the path.
- if (c.renameat2(c.AT_FDCWD, temporary.ptr, c.AT_FDCWD, destination.ptr, c.RENAME_NOREPLACE) != 0) return error.PublishFailed;
+ platform.fs.renameNoReplace(temporary.ptr, destination.ptr) catch return error.PublishFailed;
}
diff --git a/src/session_restart.zig b/src/session_restart.zig
index 3b2cceb..2d8eb59 100644
--- a/src/session_restart.zig
+++ b/src/session_restart.zig
@@ -9,7 +9,6 @@
//! socket is an argument, never `REDIWM_SOCKET`: a shell started from the live
//! session inherits that variable, and a stray run would restart the desktop.
const std = @import("std");
-const linux = std.os.linux;
const c = std.posix.system;
const platform = @import("platform");
@@ -229,13 +228,11 @@ fn waitReady(arena: std.mem.Allocator, session: Session, installed: []const u8)
return error.NotReady;
}
-const FileId = struct { dev_major: u32, dev_minor: u32, ino: u64 };
+const FileId = struct { dev: u64, ino: u64 };
fn fileId(path: [*:0]const u8) ?FileId {
- var stx: linux.Statx = undefined;
- const rc = linux.statx(linux.AT.FDCWD, path, 0, .{ .INO = true }, &stx);
- if (linux.errno(rc) != .SUCCESS) return null;
- return .{ .dev_major = stx.dev_major, .dev_minor = stx.dev_minor, .ino = stx.ino };
+ const info = platform.fs.stat(path) orelse return null;
+ return .{ .dev = info.dev, .ino = info.ino };
}
fn nowMs() i64 {
diff --git a/src/share_picker/client.zig b/src/share_picker/client.zig
index 618c2cd..753af70 100644
--- a/src/share_picker/client.zig
+++ b/src/share_picker/client.zig
@@ -3,6 +3,7 @@
//! of the test contract in tests/screencast.py.
const i18n = @import("i18n");
const std = @import("std");
+const platform = @import("platform");
const wl = @import("wayland").client.wl;
const xdg = @import("wayland").client.xdg;
const zxdg = @import("wayland").client.zxdg;
@@ -547,7 +548,7 @@ const Buffer = struct {
};
pub fn run(labels: []const []const u8) !sources.Decision {
- _ = c.signal(c.SIGPIPE, c.SIG_IGN);
+ platform.process.ignoreBrokenPipes();
const display = wl.Display.connect(null) catch return error.DisplayConnectFailed;
defer display.disconnect();
diff --git a/src/system_monitor/client.zig b/src/system_monitor/client.zig
index acfa1b0..26af4ab 100644
--- a/src/system_monitor/client.zig
+++ b/src/system_monitor/client.zig
@@ -1,6 +1,7 @@
//! Standalone System Monitor Wayland host. Uses the same decoration, input,
//! cursor and released-buffer lifecycle as the other native RediWM clients.
const std = @import("std");
+const platform = @import("platform");
const ClientCursor = @import("ui").client_cursor;
const wl = @import("wayland").client.wl;
const xdg = @import("wayland").client.xdg;
@@ -756,7 +757,7 @@ const Buffer = struct {
};
pub fn run(init: std.process.Init) !void {
- _ = c.signal(c.SIGPIPE, c.SIG_IGN);
+ platform.process.ignoreBrokenPipes();
defer @import("../files/settings.zig").deinitTheme();
var watch = try @import("settings_watch.zig").Watch.init(init.io, init.minimal.environ);
defer watch.deinit();
diff --git a/src/theme_helper/native.c b/src/theme_helper/native.c
index 4bcfd6a..31e57a1 100644
--- a/src/theme_helper/native.c
+++ b/src/theme_helper/native.c
@@ -9,7 +9,9 @@
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
+#ifdef __linux__
#include <linux/landlock.h>
+#endif
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
@@ -27,6 +29,14 @@
#define MAX_FILE (40u * 1024u * 1024u)
#define MAX_TOTAL (128u * 1024u * 1024u)
static char problem[4096];
+/* Swaps two paths atomically (RENAME_EXCHANGE). Linux only: nothing else has it. */
+static int exchange_paths(const char *a, const char *b) {
+#ifdef SYS_renameat2
+ return (int)syscall(SYS_renameat2,AT_FDCWD,a,AT_FDCWD,b,2);
+#else
+ (void)a;(void)b;errno=ENOTSUP;return -1;
+#endif
+}
static unsigned entries;
static uint64_t total;
extern int rediwm_theme_safe_path(const char *);
@@ -308,7 +318,7 @@ int rediwm_theme_publish(const char *staging,const char *destination) {
struct stat st;
if(lstat(destination,&st)==0) {
if(!S_ISDIR(st.st_mode))return fail(destination,"existing destination is not a directory");
- if(syscall(SYS_renameat2,AT_FDCWD,staging,AT_FDCWD,destination,2)<0)return fail(destination,"atomic replacement failed");
+ if(exchange_paths(staging,destination)<0)return fail(destination,"atomic replacement failed");
} else if(errno!=ENOENT || rename(staging,destination)<0)return fail(destination,"atomic install failed");
return 0;
}
@@ -346,6 +356,13 @@ int rediwm_theme_copy(const char *src,const char *dst) {total=0;return copy_file
// Image and SVG parsers run in a disposable child with no writable filesystem
// or networking. The parent performs publication only after this child exits.
static int parser_sandbox(const char *root, const char *source, int writable) {
+#ifndef __linux__
+ /* No sandbox exists here yet (a Capsicum one is planned, docs/plans/freebsd.md,
+ * P.5), and parsing untrusted packs unsandboxed is not an option. */
+ (void)root; (void)source; (void)writable;
+ errno = ENOTSUP;
+ return -1;
+#endif
struct rlimit memory={512u*1024u*1024u,512u*1024u*1024u};
if(setrlimit(RLIMIT_AS,&memory)<0)return -1;
if(rediwm_process_no_new_privileges()<0)return -1;
@@ -410,7 +427,7 @@ int rediwm_theme_stage_isolated(const char *source,const char *dest) {
int rediwm_theme_rollback(const char *staging,const char *destination) {
struct stat st;
if(lstat(staging,&st)==0) {
- if(syscall(SYS_renameat2,AT_FDCWD,staging,AT_FDCWD,destination,2)<0)return fail(destination,"install rollback failed");
+ if(exchange_paths(staging,destination)<0)return fail(destination,"install rollback failed");
} else if(errno!=ENOENT || rename(destination,staging)<0)return fail(destination,"install rollback failed");
return 0;
}