Pausa: 11 crates del fractal Ente #0 con cerebro completo
1//! Bootstrap del entorno kernel para PID 1: monta procfs/sysfs/devtmpfs/cgroup2
2//! y registra al proceso como subreaper para adoptar huérfanos.
3//!
4//! Idempotente: si los puntos de montaje ya existen (initramfs los montó),
5//! el segundo mount falla con EBUSY y simplemente lo ignoramos.
6
7use anyhow::Context;
8use nix::mount::{mount, MsFlags};
9use tracing::debug;
10
11/// Monta los pseudo-filesystems esenciales. Errores benignos (ya montados)
12/// se ignoran; errores serios se propagan.
13pub fn bootstrap_kernel_surface() -> anyhow::Result<()> {
14 // Cada uno con sus flags estándar — NOSUID/NOEXEC/NODEV donde aplica.
15 mount::<str, str, str, str>(
16 Some("proc"), "/proc", Some("proc"),
17 MsFlags::MS_NOSUID | MsFlags::MS_NOEXEC | MsFlags::MS_NODEV, None,
18 ).ok();
19 mount::<str, str, str, str>(
20 Some("sysfs"), "/sys", Some("sysfs"),
21 MsFlags::MS_NOSUID | MsFlags::MS_NOEXEC | MsFlags::MS_NODEV, None,
22 ).ok();
23 mount::<str, str, str, str>(
24 Some("devtmpfs"), "/dev", Some("devtmpfs"),
25 MsFlags::MS_NOSUID, None,
26 ).ok();
27 mount::<str, str, str, str>(
28 Some("cgroup2"), "/sys/fs/cgroup", Some("cgroup2"),
29 MsFlags::MS_NOSUID | MsFlags::MS_NOEXEC | MsFlags::MS_NODEV, None,
30 ).ok();
31 debug!("kernel surface bootstrap completo");
32 Ok(())
33}
34
35/// PR_SET_CHILD_SUBREAPER: que adoptemos huérfanos del fractal.
36///
37/// En PID 1 esto es redundante (el kernel ya lo hace), pero se deja explícito
38/// para que ente-zero corriendo como sub-init en un container mantenga la
39/// misma semántica.
40pub fn become_child_subreaper() -> anyhow::Result<()> {
41 let r = unsafe { libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1u64, 0u64, 0u64, 0u64) };
42 if r != 0 {
43 anyhow::bail!(
44 "prctl PR_SET_CHILD_SUBREAPER falló: {}",
45 std::io::Error::last_os_error()
46 );
47 }
48 Ok(())
49}
50
51/// Cosechar zombis hasta vaciar la cola de niños muertos. Devuelve los
52/// PIDs cosechados con su estado, como tuplas.
53pub fn reap_all() -> Vec<ReapedChild> {
54 use nix::errno::Errno;
55 use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
56 let mut out = Vec::new();
57 loop {
58 match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
59 Ok(WaitStatus::Exited(pid, code)) => {
60 out.push(ReapedChild { pid: pid.as_raw(), status: ReapStatus::Exited(code) });
61 }
62 Ok(WaitStatus::Signaled(pid, sig, _core)) => {
63 out.push(ReapedChild { pid: pid.as_raw(), status: ReapStatus::Signaled(sig as i32) });
64 }
65 Ok(WaitStatus::StillAlive) => return out,
66 Err(Errno::ECHILD) => return out,
67 Err(_) => return out,
68 Ok(_) => continue, // Stopped/Continued — irrelevantes
69 }
70 }
71 // unreachable, satisface al borrow checker
72 #[allow(unreachable_code)]
73 out
74}
75
76#[derive(Debug, Clone)]
77pub struct ReapedChild {
78 pub pid: i32,
79 pub status: ReapStatus,
80}
81
82#[derive(Debug, Clone)]
83pub enum ReapStatus {
84 Exited(i32),
85 Signaled(i32),
86}