Move spawn to submodule
Browse files at this commit2c01cde9beaacd8abf5f5b3117b9e006349bd633Parent: cb9dc9c4 changed files +308 -300
- src/input.rs +2 -1
- src/main.rs +2 -4
- src/utils/mod.rs +6 -295
- src/utils/spawning.rs +298 -0
src/input.rsmodified+2 -1
| @@ -24,7 +24,8 @@ use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait}; | |||
| 24 | 24 | ||
| 25 | use crate::niri::State; | 25 | use crate::niri::State; |
| 26 | use crate::screenshot_ui::ScreenshotUi; | 26 | use crate::screenshot_ui::ScreenshotUi; |
| 27 | -use crate::utils::{center, get_monotonic_time, spawn}; | 27 | +use crate::utils::spawning::spawn; |
| 28 | +use crate::utils::{center, get_monotonic_time}; | ||
| 28 | 29 | ||
| 29 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 30 | pub enum CompositorMod { | 31 | pub enum CompositorMod { |
src/main.rsmodified+2 -4
| @@ -15,10 +15,8 @@ use niri::cli::{Cli, Sub}; | |||
| 15 | use niri::dbus; | 15 | use niri::dbus; |
| 16 | use niri::ipc::client::handle_msg; | 16 | use niri::ipc::client::handle_msg; |
| 17 | use niri::niri::State; | 17 | use niri::niri::State; |
| 18 | -use niri::utils::{ | 18 | +use niri::utils::spawning::{spawn, REMOVE_ENV_RUST_BACKTRACE, REMOVE_ENV_RUST_LIB_BACKTRACE}; |
| 19 | - cause_panic, spawn, version, IS_SYSTEMD_SERVICE, REMOVE_ENV_RUST_BACKTRACE, | 19 | +use niri::utils::{cause_panic, version, IS_SYSTEMD_SERVICE}; |
| 20 | - REMOVE_ENV_RUST_LIB_BACKTRACE, | ||
| 21 | -}; | ||
| 22 | use niri::watcher::Watcher; | 20 | use niri::watcher::Watcher; |
| 23 | use niri_config::Config; | 21 | use niri_config::Config; |
| 24 | use portable_atomic::Ordering; | 22 | use portable_atomic::Ordering; |
src/utils/mod.rsmodified+6 -295
| @@ -1,27 +1,23 @@ | |||
| 1 | use std::ffi::{CString, OsStr}; | 1 | use std::ffi::{CString, OsStr}; |
| 2 | -use std::io::{self, Write}; | 2 | +use std::io::Write; |
| 3 | -use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd}; | ||
| 4 | use std::os::unix::prelude::OsStrExt; | 3 | use std::os::unix::prelude::OsStrExt; |
| 5 | -use std::os::unix::process::CommandExt; | ||
| 6 | use std::path::PathBuf; | 4 | use std::path::PathBuf; |
| 7 | -use std::process::{Command, Stdio}; | ||
| 8 | use std::ptr::null_mut; | 5 | use std::ptr::null_mut; |
| 9 | -use std::sync::atomic::{AtomicBool, Ordering}; | 6 | +use std::sync::atomic::AtomicBool; |
| 10 | -use std::thread; | ||
| 11 | use std::time::Duration; | 7 | use std::time::Duration; |
| 12 | 8 | ||
| 13 | use anyhow::{ensure, Context}; | 9 | use anyhow::{ensure, Context}; |
| 14 | use directories::UserDirs; | 10 | use directories::UserDirs; |
| 15 | use git_version::git_version; | 11 | use git_version::git_version; |
| 16 | -use libc::close_range; | ||
| 17 | use niri_config::Config; | 12 | use niri_config::Config; |
| 18 | use smithay::output::Output; | 13 | use smithay::output::Output; |
| 19 | -use smithay::reexports::rustix; | ||
| 20 | -use smithay::reexports::rustix::io::{close, read, retry_on_intr, write}; | ||
| 21 | -use smithay::reexports::rustix::pipe::{pipe_with, PipeFlags}; | ||
| 22 | use smithay::reexports::rustix::time::{clock_gettime, ClockId}; | 14 | use smithay::reexports::rustix::time::{clock_gettime, ClockId}; |
| 23 | use smithay::utils::{Logical, Point, Rectangle, Size}; | 15 | use smithay::utils::{Logical, Point, Rectangle, Size}; |
| 24 | 16 | ||
| 17 | +pub mod spawning; | ||
| 18 | + | ||
| 19 | +pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false); | ||
| 20 | + | ||
| 25 | pub fn clone2<T: Clone, U: Clone>(t: (&T, &U)) -> (T, U) { | 21 | pub fn clone2<T: Clone, U: Clone>(t: (&T, &U)) -> (T, U) { |
| 26 | (t.0.clone(), t.1.clone()) | 22 | (t.0.clone(), t.1.clone()) |
| 27 | } | 23 | } |
| @@ -83,291 +79,6 @@ pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> | |||
| 83 | Ok(Some(path)) | 79 | Ok(Some(path)) |
| 84 | } | 80 | } |
| 85 | 81 | ||
| 86 | -pub static REMOVE_ENV_RUST_BACKTRACE: AtomicBool = AtomicBool::new(false); | ||
| 87 | -pub static REMOVE_ENV_RUST_LIB_BACKTRACE: AtomicBool = AtomicBool::new(false); | ||
| 88 | - | ||
| 89 | -/// Spawns the command to run independently of the compositor. | ||
| 90 | -pub fn spawn<T: AsRef<OsStr> + Send + 'static>(command: Vec<T>) { | ||
| 91 | - let _span = tracy_client::span!(); | ||
| 92 | - | ||
| 93 | - if command.is_empty() { | ||
| 94 | - return; | ||
| 95 | - } | ||
| 96 | - | ||
| 97 | - // Spawning and waiting takes some milliseconds, so do it in a thread. | ||
| 98 | - let res = thread::Builder::new() | ||
| 99 | - .name("Command Spawner".to_owned()) | ||
| 100 | - .spawn(move || { | ||
| 101 | - let (command, args) = command.split_first().unwrap(); | ||
| 102 | - spawn_sync(command, args); | ||
| 103 | - }); | ||
| 104 | - | ||
| 105 | - if let Err(err) = res { | ||
| 106 | - warn!("error spawning a thread to spawn the command: {err:?}"); | ||
| 107 | - } | ||
| 108 | -} | ||
| 109 | - | ||
| 110 | -fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl AsRef<OsStr>>) { | ||
| 111 | - let _span = tracy_client::span!(); | ||
| 112 | - | ||
| 113 | - let command = command.as_ref(); | ||
| 114 | - | ||
| 115 | - let mut process = Command::new(command); | ||
| 116 | - process | ||
| 117 | - .args(args) | ||
| 118 | - .stdin(Stdio::null()) | ||
| 119 | - .stdout(Stdio::null()) | ||
| 120 | - .stderr(Stdio::null()); | ||
| 121 | - | ||
| 122 | - // Remove RUST_BACKTRACE and RUST_LIB_BACKTRACE from the environment if needed. | ||
| 123 | - if REMOVE_ENV_RUST_BACKTRACE.load(Ordering::Relaxed) { | ||
| 124 | - process.env_remove("RUST_BACKTRACE"); | ||
| 125 | - } | ||
| 126 | - if REMOVE_ENV_RUST_LIB_BACKTRACE.load(Ordering::Relaxed) { | ||
| 127 | - process.env_remove("RUST_LIB_BACKTRACE"); | ||
| 128 | - } | ||
| 129 | - | ||
| 130 | - // When running as a systemd session, we want to put children into their own transient scopes | ||
| 131 | - // in order to separate them from the niri process. This is helpful for example to prevent the | ||
| 132 | - // OOM killer from taking down niri together with a misbehaving client. | ||
| 133 | - // | ||
| 134 | - // Putting a child into a scope is done by calling systemd's StartTransientUnit D-Bus method | ||
| 135 | - // with a PID. Unfortunately, there seems to be a race in systemd where if the child exits at | ||
| 136 | - // just the right time, the transient unit will be created but empty, so it will linger around | ||
| 137 | - // forever. | ||
| 138 | - // | ||
| 139 | - // To prevent this, we'll use our double-fork (done for a separate reason) to help. In our | ||
| 140 | - // intermediate child we will send back the grandchild PID, and in niri we will create a | ||
| 141 | - // transient scope with both our intermediate child and the grandchild PIDs set. Only then we | ||
| 142 | - // will signal our intermediate child to exit. This way, even if the grandchild exits quickly, | ||
| 143 | - // a non-empty scope will be created (with just our intermediate child), then cleaned up when | ||
| 144 | - // our intermediate child exits. | ||
| 145 | - | ||
| 146 | - // Make a pipe to receive the grandchild PID. | ||
| 147 | - let (pipe_pid_read, pipe_pid_write) = pipe_with(PipeFlags::CLOEXEC) | ||
| 148 | - .map_err(|err| { | ||
| 149 | - warn!("error creating a pipe to transfer child PID: {err:?}"); | ||
| 150 | - }) | ||
| 151 | - .ok() | ||
| 152 | - .unzip(); | ||
| 153 | - // Make a pipe to wait in the intermediate child. | ||
| 154 | - let (pipe_wait_read, pipe_wait_write) = pipe_with(PipeFlags::CLOEXEC) | ||
| 155 | - .map_err(|err| { | ||
| 156 | - warn!("error creating a pipe for child to wait on: {err:?}"); | ||
| 157 | - }) | ||
| 158 | - .ok() | ||
| 159 | - .unzip(); | ||
| 160 | - | ||
| 161 | - unsafe { | ||
| 162 | - // The fds will be duplicated after a fork and closed on exec or exit automatically. Get | ||
| 163 | - // the raw fd inside so that it's not closed any extra times. | ||
| 164 | - let mut pipe_pid_read_fd = pipe_pid_read.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 165 | - let mut pipe_pid_write_fd = pipe_pid_write.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 166 | - let mut pipe_wait_read_fd = pipe_wait_read.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 167 | - let mut pipe_wait_write_fd = pipe_wait_write.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 168 | - | ||
| 169 | - // Double-fork to avoid having to waitpid the child. | ||
| 170 | - process.pre_exec(move || { | ||
| 171 | - // Close FDs that we don't need. Especially important for the write ones to unblock the | ||
| 172 | - // readers. | ||
| 173 | - if let Some(fd) = pipe_pid_read_fd.take() { | ||
| 174 | - close(fd); | ||
| 175 | - } | ||
| 176 | - if let Some(fd) = pipe_wait_write_fd.take() { | ||
| 177 | - close(fd); | ||
| 178 | - } | ||
| 179 | - | ||
| 180 | - // Convert the our FDs to OwnedFd, which will close them in all of our fork paths. | ||
| 181 | - let pipe_pid_write = pipe_pid_write_fd.take().map(|fd| OwnedFd::from_raw_fd(fd)); | ||
| 182 | - let pipe_wait_read = pipe_wait_read_fd.take().map(|fd| OwnedFd::from_raw_fd(fd)); | ||
| 183 | - | ||
| 184 | - match libc::fork() { | ||
| 185 | - -1 => return Err(io::Error::last_os_error()), | ||
| 186 | - 0 => (), | ||
| 187 | - grandchild_pid => { | ||
| 188 | - // Send back the PID. | ||
| 189 | - if let Some(pipe) = pipe_pid_write { | ||
| 190 | - let _ = write_all(pipe, &grandchild_pid.to_ne_bytes()); | ||
| 191 | - } | ||
| 192 | - | ||
| 193 | - // Wait until the parent signals us to exit. | ||
| 194 | - if let Some(pipe) = pipe_wait_read { | ||
| 195 | - // We're going to exit afterwards. Close all other FDs to allow | ||
| 196 | - // Command::spawn() to return in the parent process. | ||
| 197 | - let raw = pipe.as_raw_fd() as u32; | ||
| 198 | - let _ = close_range(0, raw - 1, 0); | ||
| 199 | - let _ = close_range(raw + 1, !0, 0); | ||
| 200 | - | ||
| 201 | - let _ = read_all(pipe, &mut [0]); | ||
| 202 | - } | ||
| 203 | - | ||
| 204 | - libc::_exit(0) | ||
| 205 | - } | ||
| 206 | - } | ||
| 207 | - | ||
| 208 | - Ok(()) | ||
| 209 | - }); | ||
| 210 | - } | ||
| 211 | - | ||
| 212 | - let mut child = match process.spawn() { | ||
| 213 | - Ok(child) => child, | ||
| 214 | - Err(err) => { | ||
| 215 | - warn!("error spawning {command:?}: {err:?}"); | ||
| 216 | - return; | ||
| 217 | - } | ||
| 218 | - }; | ||
| 219 | - | ||
| 220 | - drop(pipe_pid_write); | ||
| 221 | - drop(pipe_wait_read); | ||
| 222 | - | ||
| 223 | - // Wait for the grandchild PID. | ||
| 224 | - if let Some(pipe) = pipe_pid_read { | ||
| 225 | - let mut buf = [0; 4]; | ||
| 226 | - match read_all(pipe, &mut buf) { | ||
| 227 | - Ok(()) => { | ||
| 228 | - let pid = i32::from_ne_bytes(buf); | ||
| 229 | - trace!("spawned PID: {pid}"); | ||
| 230 | - | ||
| 231 | - // Start a systemd scope for the grandchild. | ||
| 232 | - #[cfg(feature = "systemd")] | ||
| 233 | - if let Err(err) = start_systemd_scope(command, child.id(), pid as u32) { | ||
| 234 | - trace!("error starting systemd scope for spawned command: {err:?}"); | ||
| 235 | - } | ||
| 236 | - } | ||
| 237 | - Err(err) => { | ||
| 238 | - warn!("error reading child PID: {err:?}"); | ||
| 239 | - } | ||
| 240 | - } | ||
| 241 | - } | ||
| 242 | - | ||
| 243 | - // Signal the intermediate child to exit now that we're done trying to creating a systemd scope. | ||
| 244 | - trace!("signaling child to exit"); | ||
| 245 | - drop(pipe_wait_write); | ||
| 246 | - | ||
| 247 | - match child.wait() { | ||
| 248 | - Ok(status) => { | ||
| 249 | - if !status.success() { | ||
| 250 | - warn!("child did not exit successfully: {status:?}"); | ||
| 251 | - } | ||
| 252 | - } | ||
| 253 | - Err(err) => { | ||
| 254 | - warn!("error waiting for child: {err:?}"); | ||
| 255 | - } | ||
| 256 | - } | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | -fn write_all(fd: impl AsFd, buf: &[u8]) -> rustix::io::Result<()> { | ||
| 260 | - let mut written = 0; | ||
| 261 | - loop { | ||
| 262 | - let n = retry_on_intr(|| write(&fd, &buf[written..]))?; | ||
| 263 | - if n == 0 { | ||
| 264 | - return Err(rustix::io::Errno::CANCELED); | ||
| 265 | - } | ||
| 266 | - | ||
| 267 | - written += n; | ||
| 268 | - if written == buf.len() { | ||
| 269 | - return Ok(()); | ||
| 270 | - } | ||
| 271 | - } | ||
| 272 | -} | ||
| 273 | - | ||
| 274 | -fn read_all(fd: impl AsFd, buf: &mut [u8]) -> rustix::io::Result<()> { | ||
| 275 | - let mut start = 0; | ||
| 276 | - loop { | ||
| 277 | - let n = retry_on_intr(|| read(&fd, &mut buf[start..]))?; | ||
| 278 | - if n == 0 { | ||
| 279 | - return Err(rustix::io::Errno::CANCELED); | ||
| 280 | - } | ||
| 281 | - | ||
| 282 | - start += n; | ||
| 283 | - if start == buf.len() { | ||
| 284 | - return Ok(()); | ||
| 285 | - } | ||
| 286 | - } | ||
| 287 | -} | ||
| 288 | - | ||
| 289 | -pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false); | ||
| 290 | - | ||
| 291 | -/// Puts a (newly spawned) pid into a transient systemd scope. | ||
| 292 | -/// | ||
| 293 | -/// This separates the pid from the compositor scope, which for example prevents the OOM killer | ||
| 294 | -/// from bringing down the compositor together with a misbehaving client. | ||
| 295 | -#[cfg(feature = "systemd")] | ||
| 296 | -fn start_systemd_scope(name: &OsStr, intermediate_pid: u32, child_pid: u32) -> anyhow::Result<()> { | ||
| 297 | - use std::fmt::Write as _; | ||
| 298 | - use std::path::Path; | ||
| 299 | - use std::sync::OnceLock; | ||
| 300 | - | ||
| 301 | - use zbus::zvariant::{OwnedObjectPath, Value}; | ||
| 302 | - | ||
| 303 | - // We only start transient scopes if we're a systemd service ourselves. | ||
| 304 | - if !IS_SYSTEMD_SERVICE.load(Ordering::Relaxed) { | ||
| 305 | - return Ok(()); | ||
| 306 | - } | ||
| 307 | - | ||
| 308 | - let _span = tracy_client::span!(); | ||
| 309 | - | ||
| 310 | - // Extract the basename. | ||
| 311 | - let name = Path::new(name).file_name().unwrap_or(name); | ||
| 312 | - | ||
| 313 | - let mut scope_name = String::from("app-niri-"); | ||
| 314 | - | ||
| 315 | - // Escape for systemd similarly to libgnome-desktop, which says it had adapted this from | ||
| 316 | - // systemd source. | ||
| 317 | - for &c in name.as_bytes() { | ||
| 318 | - if c.is_ascii_alphanumeric() || matches!(c, b':' | b'_' | b'.') { | ||
| 319 | - scope_name.push(char::from(c)); | ||
| 320 | - } else { | ||
| 321 | - let _ = write!(scope_name, "\\x{c:02x}"); | ||
| 322 | - } | ||
| 323 | - } | ||
| 324 | - | ||
| 325 | - let _ = write!(scope_name, "-{child_pid}.scope"); | ||
| 326 | - | ||
| 327 | - // Ask systemd to start a transient scope. | ||
| 328 | - static CONNECTION: OnceLock<zbus::Result<zbus::blocking::Connection>> = OnceLock::new(); | ||
| 329 | - let conn = CONNECTION | ||
| 330 | - .get_or_init(zbus::blocking::Connection::session) | ||
| 331 | - .clone() | ||
| 332 | - .context("error connecting to session bus")?; | ||
| 333 | - | ||
| 334 | - let proxy = zbus::blocking::Proxy::new( | ||
| 335 | - &conn, | ||
| 336 | - "org.freedesktop.systemd1", | ||
| 337 | - "/org/freedesktop/systemd1", | ||
| 338 | - "org.freedesktop.systemd1.Manager", | ||
| 339 | - ) | ||
| 340 | - .context("error creating a Proxy")?; | ||
| 341 | - | ||
| 342 | - let signals = proxy | ||
| 343 | - .receive_signal("JobRemoved") | ||
| 344 | - .context("error creating a signal iterator")?; | ||
| 345 | - | ||
| 346 | - let pids: &[_] = &[intermediate_pid, child_pid]; | ||
| 347 | - let properties: &[_] = &[ | ||
| 348 | - ("PIDs", Value::new(pids)), | ||
| 349 | - ("CollectMode", Value::new("inactive-or-failed")), | ||
| 350 | - ]; | ||
| 351 | - let aux: &[(&str, &[(&str, Value)])] = &[]; | ||
| 352 | - | ||
| 353 | - let job: OwnedObjectPath = proxy | ||
| 354 | - .call("StartTransientUnit", &(scope_name, "fail", properties, aux)) | ||
| 355 | - .context("error calling StartTransientUnit")?; | ||
| 356 | - | ||
| 357 | - trace!("waiting for JobRemoved"); | ||
| 358 | - for message in signals { | ||
| 359 | - let body: (u32, OwnedObjectPath, &str, &str) = | ||
| 360 | - message.body().context("error parsing signal")?; | ||
| 361 | - | ||
| 362 | - if body.1 == job { | ||
| 363 | - // Our transient unit had started, we're good to exit the intermediate child. | ||
| 364 | - break; | ||
| 365 | - } | ||
| 366 | - } | ||
| 367 | - | ||
| 368 | - Ok(()) | ||
| 369 | -} | ||
| 370 | - | ||
| 371 | pub fn write_png_rgba8( | 82 | pub fn write_png_rgba8( |
| 372 | w: impl Write, | 83 | w: impl Write, |
| 373 | width: u32, | 84 | width: u32, |
src/utils/spawning.rsadded+298 -0
| @@ -0,0 +1,298 @@ | |||
| 1 | +use std::ffi::OsStr; | ||
| 2 | +use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd}; | ||
| 3 | +use std::os::unix::process::CommandExt; | ||
| 4 | +use std::process::{Command, Stdio}; | ||
| 5 | +use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 6 | +use std::{io, thread}; | ||
| 7 | + | ||
| 8 | +use libc::close_range; | ||
| 9 | +use smithay::reexports::rustix; | ||
| 10 | +use smithay::reexports::rustix::io::{close, read, retry_on_intr, write}; | ||
| 11 | +use smithay::reexports::rustix::pipe::{pipe_with, PipeFlags}; | ||
| 12 | + | ||
| 13 | +pub static REMOVE_ENV_RUST_BACKTRACE: AtomicBool = AtomicBool::new(false); | ||
| 14 | +pub static REMOVE_ENV_RUST_LIB_BACKTRACE: AtomicBool = AtomicBool::new(false); | ||
| 15 | + | ||
| 16 | +/// Spawns the command to run independently of the compositor. | ||
| 17 | +pub fn spawn<T: AsRef<OsStr> + Send + 'static>(command: Vec<T>) { | ||
| 18 | + let _span = tracy_client::span!(); | ||
| 19 | + | ||
| 20 | + if command.is_empty() { | ||
| 21 | + return; | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + // Spawning and waiting takes some milliseconds, so do it in a thread. | ||
| 25 | + let res = thread::Builder::new() | ||
| 26 | + .name("Command Spawner".to_owned()) | ||
| 27 | + .spawn(move || { | ||
| 28 | + let (command, args) = command.split_first().unwrap(); | ||
| 29 | + spawn_sync(command, args); | ||
| 30 | + }); | ||
| 31 | + | ||
| 32 | + if let Err(err) = res { | ||
| 33 | + warn!("error spawning a thread to spawn the command: {err:?}"); | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl AsRef<OsStr>>) { | ||
| 38 | + let _span = tracy_client::span!(); | ||
| 39 | + | ||
| 40 | + let command = command.as_ref(); | ||
| 41 | + | ||
| 42 | + let mut process = Command::new(command); | ||
| 43 | + process | ||
| 44 | + .args(args) | ||
| 45 | + .stdin(Stdio::null()) | ||
| 46 | + .stdout(Stdio::null()) | ||
| 47 | + .stderr(Stdio::null()); | ||
| 48 | + | ||
| 49 | + // Remove RUST_BACKTRACE and RUST_LIB_BACKTRACE from the environment if needed. | ||
| 50 | + if REMOVE_ENV_RUST_BACKTRACE.load(Ordering::Relaxed) { | ||
| 51 | + process.env_remove("RUST_BACKTRACE"); | ||
| 52 | + } | ||
| 53 | + if REMOVE_ENV_RUST_LIB_BACKTRACE.load(Ordering::Relaxed) { | ||
| 54 | + process.env_remove("RUST_LIB_BACKTRACE"); | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + // When running as a systemd session, we want to put children into their own transient scopes | ||
| 58 | + // in order to separate them from the niri process. This is helpful for example to prevent the | ||
| 59 | + // OOM killer from taking down niri together with a misbehaving client. | ||
| 60 | + // | ||
| 61 | + // Putting a child into a scope is done by calling systemd's StartTransientUnit D-Bus method | ||
| 62 | + // with a PID. Unfortunately, there seems to be a race in systemd where if the child exits at | ||
| 63 | + // just the right time, the transient unit will be created but empty, so it will linger around | ||
| 64 | + // forever. | ||
| 65 | + // | ||
| 66 | + // To prevent this, we'll use our double-fork (done for a separate reason) to help. In our | ||
| 67 | + // intermediate child we will send back the grandchild PID, and in niri we will create a | ||
| 68 | + // transient scope with both our intermediate child and the grandchild PIDs set. Only then we | ||
| 69 | + // will signal our intermediate child to exit. This way, even if the grandchild exits quickly, | ||
| 70 | + // a non-empty scope will be created (with just our intermediate child), then cleaned up when | ||
| 71 | + // our intermediate child exits. | ||
| 72 | + | ||
| 73 | + // Make a pipe to receive the grandchild PID. | ||
| 74 | + let (pipe_pid_read, pipe_pid_write) = pipe_with(PipeFlags::CLOEXEC) | ||
| 75 | + .map_err(|err| { | ||
| 76 | + warn!("error creating a pipe to transfer child PID: {err:?}"); | ||
| 77 | + }) | ||
| 78 | + .ok() | ||
| 79 | + .unzip(); | ||
| 80 | + // Make a pipe to wait in the intermediate child. | ||
| 81 | + let (pipe_wait_read, pipe_wait_write) = pipe_with(PipeFlags::CLOEXEC) | ||
| 82 | + .map_err(|err| { | ||
| 83 | + warn!("error creating a pipe for child to wait on: {err:?}"); | ||
| 84 | + }) | ||
| 85 | + .ok() | ||
| 86 | + .unzip(); | ||
| 87 | + | ||
| 88 | + unsafe { | ||
| 89 | + // The fds will be duplicated after a fork and closed on exec or exit automatically. Get | ||
| 90 | + // the raw fd inside so that it's not closed any extra times. | ||
| 91 | + let mut pipe_pid_read_fd = pipe_pid_read.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 92 | + let mut pipe_pid_write_fd = pipe_pid_write.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 93 | + let mut pipe_wait_read_fd = pipe_wait_read.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 94 | + let mut pipe_wait_write_fd = pipe_wait_write.as_ref().map(|fd| fd.as_raw_fd()); | ||
| 95 | + | ||
| 96 | + // Double-fork to avoid having to waitpid the child. | ||
| 97 | + process.pre_exec(move || { | ||
| 98 | + // Close FDs that we don't need. Especially important for the write ones to unblock the | ||
| 99 | + // readers. | ||
| 100 | + if let Some(fd) = pipe_pid_read_fd.take() { | ||
| 101 | + close(fd); | ||
| 102 | + } | ||
| 103 | + if let Some(fd) = pipe_wait_write_fd.take() { | ||
| 104 | + close(fd); | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + // Convert the our FDs to OwnedFd, which will close them in all of our fork paths. | ||
| 108 | + let pipe_pid_write = pipe_pid_write_fd.take().map(|fd| OwnedFd::from_raw_fd(fd)); | ||
| 109 | + let pipe_wait_read = pipe_wait_read_fd.take().map(|fd| OwnedFd::from_raw_fd(fd)); | ||
| 110 | + | ||
| 111 | + match libc::fork() { | ||
| 112 | + -1 => return Err(io::Error::last_os_error()), | ||
| 113 | + 0 => (), | ||
| 114 | + grandchild_pid => { | ||
| 115 | + // Send back the PID. | ||
| 116 | + if let Some(pipe) = pipe_pid_write { | ||
| 117 | + let _ = write_all(pipe, &grandchild_pid.to_ne_bytes()); | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + // Wait until the parent signals us to exit. | ||
| 121 | + if let Some(pipe) = pipe_wait_read { | ||
| 122 | + // We're going to exit afterwards. Close all other FDs to allow | ||
| 123 | + // Command::spawn() to return in the parent process. | ||
| 124 | + let raw = pipe.as_raw_fd() as u32; | ||
| 125 | + let _ = close_range(0, raw - 1, 0); | ||
| 126 | + let _ = close_range(raw + 1, !0, 0); | ||
| 127 | + | ||
| 128 | + let _ = read_all(pipe, &mut [0]); | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + libc::_exit(0) | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + Ok(()) | ||
| 136 | + }); | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + let mut child = match process.spawn() { | ||
| 140 | + Ok(child) => child, | ||
| 141 | + Err(err) => { | ||
| 142 | + warn!("error spawning {command:?}: {err:?}"); | ||
| 143 | + return; | ||
| 144 | + } | ||
| 145 | + }; | ||
| 146 | + | ||
| 147 | + drop(pipe_pid_write); | ||
| 148 | + drop(pipe_wait_read); | ||
| 149 | + | ||
| 150 | + // Wait for the grandchild PID. | ||
| 151 | + if let Some(pipe) = pipe_pid_read { | ||
| 152 | + let mut buf = [0; 4]; | ||
| 153 | + match read_all(pipe, &mut buf) { | ||
| 154 | + Ok(()) => { | ||
| 155 | + let pid = i32::from_ne_bytes(buf); | ||
| 156 | + trace!("spawned PID: {pid}"); | ||
| 157 | + | ||
| 158 | + // Start a systemd scope for the grandchild. | ||
| 159 | + #[cfg(feature = "systemd")] | ||
| 160 | + if let Err(err) = start_systemd_scope(command, child.id(), pid as u32) { | ||
| 161 | + trace!("error starting systemd scope for spawned command: {err:?}"); | ||
| 162 | + } | ||
| 163 | + } | ||
| 164 | + Err(err) => { | ||
| 165 | + warn!("error reading child PID: {err:?}"); | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + // Signal the intermediate child to exit now that we're done trying to creating a systemd scope. | ||
| 171 | + trace!("signaling child to exit"); | ||
| 172 | + drop(pipe_wait_write); | ||
| 173 | + | ||
| 174 | + match child.wait() { | ||
| 175 | + Ok(status) => { | ||
| 176 | + if !status.success() { | ||
| 177 | + warn!("child did not exit successfully: {status:?}"); | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | + Err(err) => { | ||
| 181 | + warn!("error waiting for child: {err:?}"); | ||
| 182 | + } | ||
| 183 | + } | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +fn write_all(fd: impl AsFd, buf: &[u8]) -> rustix::io::Result<()> { | ||
| 187 | + let mut written = 0; | ||
| 188 | + loop { | ||
| 189 | + let n = retry_on_intr(|| write(&fd, &buf[written..]))?; | ||
| 190 | + if n == 0 { | ||
| 191 | + return Err(rustix::io::Errno::CANCELED); | ||
| 192 | + } | ||
| 193 | + | ||
| 194 | + written += n; | ||
| 195 | + if written == buf.len() { | ||
| 196 | + return Ok(()); | ||
| 197 | + } | ||
| 198 | + } | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +fn read_all(fd: impl AsFd, buf: &mut [u8]) -> rustix::io::Result<()> { | ||
| 202 | + let mut start = 0; | ||
| 203 | + loop { | ||
| 204 | + let n = retry_on_intr(|| read(&fd, &mut buf[start..]))?; | ||
| 205 | + if n == 0 { | ||
| 206 | + return Err(rustix::io::Errno::CANCELED); | ||
| 207 | + } | ||
| 208 | + | ||
| 209 | + start += n; | ||
| 210 | + if start == buf.len() { | ||
| 211 | + return Ok(()); | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +/// Puts a (newly spawned) pid into a transient systemd scope. | ||
| 217 | +/// | ||
| 218 | +/// This separates the pid from the compositor scope, which for example prevents the OOM killer | ||
| 219 | +/// from bringing down the compositor together with a misbehaving client. | ||
| 220 | +#[cfg(feature = "systemd")] | ||
| 221 | +fn start_systemd_scope(name: &OsStr, intermediate_pid: u32, child_pid: u32) -> anyhow::Result<()> { | ||
| 222 | + use std::fmt::Write as _; | ||
| 223 | + use std::os::unix::ffi::OsStrExt; | ||
| 224 | + use std::path::Path; | ||
| 225 | + use std::sync::OnceLock; | ||
| 226 | + | ||
| 227 | + use anyhow::Context; | ||
| 228 | + use zbus::zvariant::{OwnedObjectPath, Value}; | ||
| 229 | + | ||
| 230 | + use crate::utils::IS_SYSTEMD_SERVICE; | ||
| 231 | + | ||
| 232 | + // We only start transient scopes if we're a systemd service ourselves. | ||
| 233 | + if !IS_SYSTEMD_SERVICE.load(Ordering::Relaxed) { | ||
| 234 | + return Ok(()); | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + let _span = tracy_client::span!(); | ||
| 238 | + | ||
| 239 | + // Extract the basename. | ||
| 240 | + let name = Path::new(name).file_name().unwrap_or(name); | ||
| 241 | + | ||
| 242 | + let mut scope_name = String::from("app-niri-"); | ||
| 243 | + | ||
| 244 | + // Escape for systemd similarly to libgnome-desktop, which says it had adapted this from | ||
| 245 | + // systemd source. | ||
| 246 | + for &c in name.as_bytes() { | ||
| 247 | + if c.is_ascii_alphanumeric() || matches!(c, b':' | b'_' | b'.') { | ||
| 248 | + scope_name.push(char::from(c)); | ||
| 249 | + } else { | ||
| 250 | + let _ = write!(scope_name, "\\x{c:02x}"); | ||
| 251 | + } | ||
| 252 | + } | ||
| 253 | + | ||
| 254 | + let _ = write!(scope_name, "-{child_pid}.scope"); | ||
| 255 | + | ||
| 256 | + // Ask systemd to start a transient scope. | ||
| 257 | + static CONNECTION: OnceLock<zbus::Result<zbus::blocking::Connection>> = OnceLock::new(); | ||
| 258 | + let conn = CONNECTION | ||
| 259 | + .get_or_init(zbus::blocking::Connection::session) | ||
| 260 | + .clone() | ||
| 261 | + .context("error connecting to session bus")?; | ||
| 262 | + | ||
| 263 | + let proxy = zbus::blocking::Proxy::new( | ||
| 264 | + &conn, | ||
| 265 | + "org.freedesktop.systemd1", | ||
| 266 | + "/org/freedesktop/systemd1", | ||
| 267 | + "org.freedesktop.systemd1.Manager", | ||
| 268 | + ) | ||
| 269 | + .context("error creating a Proxy")?; | ||
| 270 | + | ||
| 271 | + let signals = proxy | ||
| 272 | + .receive_signal("JobRemoved") | ||
| 273 | + .context("error creating a signal iterator")?; | ||
| 274 | + | ||
| 275 | + let pids: &[_] = &[intermediate_pid, child_pid]; | ||
| 276 | + let properties: &[_] = &[ | ||
| 277 | + ("PIDs", Value::new(pids)), | ||
| 278 | + ("CollectMode", Value::new("inactive-or-failed")), | ||
| 279 | + ]; | ||
| 280 | + let aux: &[(&str, &[(&str, Value)])] = &[]; | ||
| 281 | + | ||
| 282 | + let job: OwnedObjectPath = proxy | ||
| 283 | + .call("StartTransientUnit", &(scope_name, "fail", properties, aux)) | ||
| 284 | + .context("error calling StartTransientUnit")?; | ||
| 285 | + | ||
| 286 | + trace!("waiting for JobRemoved"); | ||
| 287 | + for message in signals { | ||
| 288 | + let body: (u32, OwnedObjectPath, &str, &str) = | ||
| 289 | + message.body().context("error parsing signal")?; | ||
| 290 | + | ||
| 291 | + if body.1 == job { | ||
| 292 | + // Our transient unit had started, we're good to exit the intermediate child. | ||
| 293 | + break; | ||
| 294 | + } | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + Ok(()) | ||
| 298 | +} | ||