Skip to main content

detcore/syscalls/
namespace.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9//! Deterministic views of kernel namespace metadata.
10
11#[cfg(test)]
12#[path = "namespace/own_getters_tests.rs"]
13mod own_getters_tests;
14
15use std::ffi::OsStr;
16use std::os::unix::ffi::OsStrExt;
17use std::path::Component;
18use std::path::Path;
19use std::path::PathBuf;
20use std::sync::Arc;
21
22use reverie::Errno;
23use reverie::Error;
24use reverie::Guest;
25use reverie::Stack;
26use reverie::syscalls;
27use reverie::syscalls::AddrMut;
28use reverie::syscalls::MemoryAccess;
29use reverie::syscalls::PathPtr;
30use reverie::syscalls::ReadAddr;
31use reverie::syscalls::Syscall;
32
33use super::deterministic_stdio_inode;
34use super::deterministic_stdio_inode_for_resource;
35use crate::record_or_replay::RecordOrReplay;
36use crate::tool_global::determinize_inode;
37use crate::tool_local::Detcore;
38use crate::types::DetInode;
39use crate::types::RawInode;
40
41// AUTONOMOUS-BOT-IMPLEMENTED
42// TODO-HUMAN-REVIEW(#877)
43fn is_proc_id(component: &OsStr) -> bool {
44    component == "self"
45        || component == "thread-self"
46        || component.to_str().is_some_and(|value| {
47            !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit())
48        })
49}
50
51// AUTONOMOUS-BOT-IMPLEMENTED
52// TODO-HUMAN-REVIEW(#877)
53fn canonical_namespace_name(name: &OsStr) -> Option<&'static [u8]> {
54    match name.to_str()? {
55        "cgroup" => Some(b"cgroup:[4026531835]"),
56        "ipc" => Some(b"ipc:[4026531839]"),
57        "mnt" => Some(b"mnt:[4026531841]"),
58        "net" => Some(b"net:[4026531840]"),
59        "pid" | "pid_for_children" => Some(b"pid:[4026531836]"),
60        "time" | "time_for_children" => Some(b"time:[4026531834]"),
61        "user" => Some(b"user:[4026531837]"),
62        "uts" => Some(b"uts:[4026531838]"),
63        _ => None,
64    }
65}
66
67// AUTONOMOUS-BOT-IMPLEMENTED
68// TODO-HUMAN-REVIEW(#877)
69fn canonical_namespace_target(path: &Path) -> Option<&'static [u8]> {
70    if !path.is_absolute() {
71        return None;
72    }
73
74    let mut parts = Vec::new();
75    for component in path.components() {
76        match component {
77            Component::RootDir => {}
78            Component::Normal(part) => parts.push(part),
79            Component::CurDir | Component::ParentDir | Component::Prefix(_) => return None,
80        }
81    }
82
83    let namespace = match parts.as_slice() {
84        [proc, subject, ns, namespace] if *proc == "proc" && is_proc_id(subject) && *ns == "ns" => {
85            namespace
86        }
87        [proc, subject, task, tid, ns, namespace]
88            if *proc == "proc"
89                && is_proc_id(subject)
90                && *task == "task"
91                && is_proc_id(tid)
92                && *ns == "ns" =>
93        {
94            namespace
95        }
96        _ => return None,
97    };
98    canonical_namespace_name(namespace)
99}
100
101// AUTONOMOUS-BOT-IMPLEMENTED
102// TODO-HUMAN-REVIEW(PR-972): Review proc-fd path alias coverage.
103fn normalized_absolute_parts(path: &Path) -> Option<Vec<&OsStr>> {
104    if !path.is_absolute() {
105        return None;
106    }
107
108    let mut parts = Vec::new();
109    for component in path.components() {
110        match component {
111            Component::RootDir | Component::CurDir => {}
112            Component::Normal(part) => parts.push(part),
113            Component::ParentDir => {
114                parts.pop()?;
115            }
116            Component::Prefix(_) => return None,
117        }
118    }
119    Some(parts)
120}
121
122fn decimal_u32(component: &OsStr) -> Option<u32> {
123    let value = component.to_str()?;
124    (!value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()))
125        .then(|| value.parse().ok())?
126}
127
128fn decimal_fd(component: &OsStr) -> Option<i32> {
129    let value = component.to_str()?;
130    // procfs names descriptors without leading zeros (`name_to_int`).
131    (!value.is_empty()
132        && value.bytes().all(|byte| byte.is_ascii_digit())
133        && (value == "0" || !value.starts_with('0')))
134    .then(|| value.parse().ok())?
135}
136
137/// The bytes of a readlink buffer that a placeholder's link may cover, read
138/// before the kernel writes the link (`restore_link_tail`).
139pub(crate) fn saved_link_bytes<G: Guest<Detcore<T>>, T: RecordOrReplay>(
140    guest: &G,
141    buffer: Option<AddrMut<'_, libc::c_char>>,
142    buffer_len: usize,
143) -> Option<Vec<u8>> {
144    // Also what a pipe or socket link's canonicalization restores, so it is
145    // read for every link, not only a placeholder's.
146    saved_link_prefix(
147        guest,
148        buffer,
149        buffer_len.min(ANONYMOUS_PROC_FD_TARGET_CAPACITY),
150    )
151}
152
153/// The bytes of a readlink buffer that the kernel's answer for an `exe` link
154/// may cover, read before the kernel writes it: as many as a path Linux
155/// renders can have, so that every byte past a shorter substituted target
156/// is restored (`Detcore::substitute_exe_link`).
157fn saved_exe_link_bytes<G: Guest<Detcore<T>>, T: RecordOrReplay>(
158    guest: &G,
159    buffer: Option<AddrMut<'_, libc::c_char>>,
160    buffer_len: usize,
161) -> Option<Vec<u8>> {
162    saved_link_prefix(guest, buffer, buffer_len.min(libc::PATH_MAX as usize))
163}
164
165/// The first `len` bytes of a readlink buffer, or its readable prefix.
166fn saved_link_prefix<G: Guest<Detcore<T>>, T: RecordOrReplay>(
167    guest: &G,
168    buffer: Option<AddrMut<'_, libc::c_char>>,
169    len: usize,
170) -> Option<Vec<u8>> {
171    let buffer = buffer?;
172    let mut saved = vec![0; len];
173    if guest
174        .memory()
175        .read_exact(buffer.cast::<u8>(), &mut saved)
176        .is_ok()
177    {
178        return Some(saved);
179    }
180    // The readable prefix, a page at a time: a buffer may run into an
181    // unmapped page past the link the kernel writes.
182    const PAGE: usize = 4096;
183    let start = buffer.as_raw();
184    let mut read = 0;
185    while read < saved.len() {
186        let end = (((start + read) / PAGE + 1) * PAGE - start).min(saved.len());
187        // SAFETY: `read < saved.len() <= buffer_len`, so the address stays
188        // inside the guest's buffer; nothing is dereferenced here.
189        let chunk = unsafe { buffer.cast::<u8>().add(read) };
190        if guest
191            .memory()
192            .read_exact(chunk, &mut saved[read..end])
193            .is_err()
194        {
195            break;
196        }
197        read = end;
198    }
199    saved.truncate(read);
200    (read > 0).then_some(saved)
201}
202
203/// Put back the caller's bytes after a rewritten link of `written` bytes,
204/// where the kernel had written `kernel_len`: Linux writes only the link.
205pub(crate) fn restore_link_tail<G: Guest<Detcore<T>>, T: RecordOrReplay>(
206    guest: &mut G,
207    buffer: AddrMut<'_, libc::c_char>,
208    written: usize,
209    kernel_len: usize,
210    saved: Option<&[u8]>,
211) -> Result<(), Error> {
212    if let Some(saved) = saved {
213        let end = kernel_len.min(saved.len());
214        if written < end {
215            // SAFETY: `written < end <= saved.len() <= buffer_len`, so the
216            // address stays inside the guest's buffer; nothing is dereferenced
217            // here, only written through the guest memory interface.
218            let tail = unsafe { buffer.cast::<u8>().add(written) };
219            guest.memory().write_exact(tail, &saved[written..end])?;
220        }
221    }
222    Ok(())
223}
224
225/// Whether `path` spells a task's descriptor link,
226/// `/proc/<pid>/task/<tid>/fd/N`.
227fn names_task_descriptor_link(path: &Path) -> bool {
228    let Some(parts) = normalized_absolute_parts(path) else {
229        return false;
230    };
231    matches!(
232        parts.as_slice(),
233        [proc, _, task, _, fd_dir, fd]
234            if *proc == "proc" && *task == "task" && *fd_dir == "fd" && decimal_fd(fd).is_some()
235    )
236}
237
238/// Returns the optional numeric proc subject and the descriptor number.
239pub(crate) fn proc_fd_target(path: &Path) -> Option<(Option<u32>, i32)> {
240    let parts = normalized_absolute_parts(path)?;
241    match parts.as_slice() {
242        [dev, fd_dir, fd] if *dev == "dev" && *fd_dir == "fd" => Some((None, decimal_fd(fd)?)),
243        [proc, subject, fd_dir, fd] if *proc == "proc" && *fd_dir == "fd" => {
244            let subject = match subject.to_str()? {
245                "self" | "thread-self" => None,
246                _ => Some(decimal_u32(subject)?),
247            };
248            Some((subject, decimal_fd(fd)?))
249        }
250        _ => None,
251    }
252}
253
254/// Whose descriptor table a descriptor link names.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub(crate) enum DescriptorTable {
257    /// The process's: `/proc/self/fd/N`, `/proc/<pid>/fd/N` and `/dev/fd/N`
258    /// (a symbolic link to `/proc/self/fd`). procfs reads it from the
259    /// thread-group leader, whose table a thread cloned without `CLONE_FILES`
260    /// does not share.
261    Process,
262    /// The calling thread's own: `/proc/thread-self/fd/N` and
263    /// `/proc/<pid>/task/<tid>/fd/N`.
264    Thread,
265}
266
267/// A descriptor that a descriptor link of the caller names, by number, and
268/// the table it is read from.
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270pub(crate) struct DescriptorLink {
271    pub(crate) fd: i32,
272    pub(crate) table: DescriptorTable,
273}
274
275/// The descriptor that the absolute guest path `path` names through one of
276/// the caller's descriptor links, and whose table that is:
277/// `/dev/fd/N`, `/proc/self/fd/N` and `/proc/<pid>/fd/N` for the caller's
278/// own pid name the process's table ([`DescriptorTable::Process`]);
279/// `/proc/thread-self/fd/N` and `/proc/<pid>/task/<tid>/fd/N` (or
280/// `/proc/self/task/<tid>/fd/N`) for its own pid and tid name the calling
281/// thread's ([`DescriptorTable::Thread`]). `own` is the caller's (pid, tid)
282/// as the guest's numeric `/proc` spellings name them (Detcore's, see
283/// `Detcore::procfs_caller_ids`), or `None` where Detcore does not know
284/// those names (in a nested PID namespace), which recognizes only the
285/// spellings without numbers. `None` for a spelling with `..`: the kernel walks it through the
286/// directory the link reaches, not lexically. A sibling thread's directory
287/// is not recognized, since that thread may have a descriptor table of its
288/// own.
289pub(crate) fn own_descriptor_link(path: &Path, own: Option<(i32, i32)>) -> Option<DescriptorLink> {
290    if !path.is_absolute() {
291        return None;
292    }
293    let mut parts = Vec::new();
294    for component in path.components() {
295        match component {
296            Component::RootDir | Component::CurDir => {}
297            Component::Normal(part) => parts.push(part),
298            Component::ParentDir | Component::Prefix(_) => return None,
299        }
300    }
301    let own_process = |part: &OsStr| {
302        part == "self" || own.is_some_and(|(pid, _)| part.to_str() == Some(&pid.to_string()))
303    };
304    let own_thread =
305        |part: &OsStr| own.is_some_and(|(_, tid)| part.to_str() == Some(&tid.to_string()));
306    let link = |fd: &OsStr, table| decimal_fd(fd).map(|fd| DescriptorLink { fd, table });
307    match parts.as_slice() {
308        [dev, fd_dir, fd] if *dev == "dev" && *fd_dir == "fd" => link(fd, DescriptorTable::Process),
309        [proc, subject, fd_dir, fd]
310            if *proc == "proc" && *fd_dir == "fd" && *subject == "thread-self" =>
311        {
312            link(fd, DescriptorTable::Thread)
313        }
314        [proc, subject, fd_dir, fd]
315            if *proc == "proc" && *fd_dir == "fd" && own_process(subject) =>
316        {
317            link(fd, DescriptorTable::Process)
318        }
319        [proc, subject, task, thread, fd_dir, fd]
320            if *proc == "proc"
321                && *task == "task"
322                && *fd_dir == "fd"
323                && own_process(subject)
324                && own_thread(thread) =>
325        {
326            link(fd, DescriptorTable::Thread)
327        }
328        _ => None,
329    }
330}
331
332/// Whether the absolute guest path `path` names something through a
333/// selector that procfs or `/dev` resolves for whoever looks it up:
334/// `/proc/self`, `/proc/thread-self`, `/proc/mounts` and `/proc/net` (links
335/// into `self`), `/dev/fd`, and `/dev/stdin`, `/dev/stdout` and `/dev/stderr`
336/// (links into `/proc/self/fd`), or anything below them. A descriptor opened
337/// at such a path is the opener's file, so the path cannot stand for that
338/// descriptor in another process or thread. A spelling with `..`, or a
339/// relative one, is treated the same way, since it is not resolved
340/// lexically.
341pub(crate) fn names_through_caller_selector(path: &Path) -> bool {
342    if !path.is_absolute() {
343        return true;
344    }
345    let mut parts = Vec::new();
346    for component in path.components() {
347        match component {
348            Component::RootDir | Component::CurDir => {}
349            Component::Normal(part) => parts.push(part),
350            Component::ParentDir | Component::Prefix(_) => return true,
351        }
352    }
353    match parts.as_slice() {
354        [proc, selector, ..] if *proc == "proc" => {
355            ["self", "thread-self", "mounts", "net"].contains(&selector.to_str().unwrap_or(""))
356        }
357        [dev, selector, ..] if *dev == "dev" => {
358            ["fd", "stdin", "stdout", "stderr"].contains(&selector.to_str().unwrap_or(""))
359        }
360        _ => false,
361    }
362}
363
364/// The optional numeric proc subject and descriptor number of a descriptor
365/// link spelled with leading zeros (`/proc/self/fd/03`, `/dev/fd/03`), which
366/// procfs does not have.
367pub(crate) fn proc_fd_target_with_leading_zeros(path: &Path) -> Option<(Option<u32>, i32)> {
368    let parts = normalized_absolute_parts(path)?;
369    let (subject, fd) = match parts.as_slice() {
370        [dev, fd_dir, fd] if *dev == "dev" && *fd_dir == "fd" => (None, fd),
371        [proc, subject, fd_dir, fd] if *proc == "proc" && *fd_dir == "fd" => (Some(subject), fd),
372        _ => return None,
373    };
374    let fd = fd.to_str()?;
375    if fd.len() < 2 || !fd.starts_with('0') || !fd.bytes().all(|byte| byte.is_ascii_digit()) {
376        return None;
377    }
378    let subject = match subject {
379        None => None,
380        Some(subject) => match subject.to_str()? {
381            "self" | "thread-self" => None,
382            _ => Some(decimal_u32(subject)?),
383        },
384    };
385    Some((subject, fd.parse().ok()?))
386}
387
388/// A `/proc` link whose target Detcore decides itself
389/// ([`decided_procfs_link`]).
390#[derive(Debug, PartialEq, Eq)]
391enum DecidedLink {
392    /// The link's target.
393    Target(Vec<u8>),
394    /// The caller's own descriptor link, by a spelling the backend may not
395    /// answer (`/proc/self/task/<tid>/fd/N`): read as `/proc/self/fd/N`.
396    SelfFd(i32),
397    /// A spelling that follows a decided link (a trailing slash or `.`) and
398    /// so names no link: `EINVAL` where the target is a directory, `ENOTDIR`
399    /// where it is a file.
400    Followed(Errno),
401}
402
403/// The number of bytes `readlink` may copy for a `bufsiz` argument of
404/// `buffer_len`, which Linux takes as an `int`: EINVAL unless positive.
405pub(crate) fn readlink_size(buffer_len: usize) -> Result<usize, Errno> {
406    let size = buffer_len as u32 as i32;
407    if size <= 0 {
408        return Err(Errno::EINVAL);
409    }
410    Ok(size as usize)
411}
412
413/// The link at the absolute spelling `path` whose target Detcore decides from
414/// its own model, for a caller whose pid and tid, as the guest sees them, are
415/// `pid` and `tid`: `self` names the pid and `thread-self` the pid's task
416/// `tid`; the `mounts` and `net` links name `self/mounts` and `self/net`; the
417/// caller's namespace links name their canonical constants; and the caller's
418/// own descriptor link spelled through its thread is its `fd/N`. A trailing
419/// slash or `.` follows the link, so such a spelling of a decided target is
420/// [`DecidedLink::Followed`]. `None` for any other path, for a spelling with
421/// `..`, and for a followed descriptor link, which the kernel resolves.
422fn decided_procfs_link(path: &[u8], pid: i32, tid: i32) -> Option<DecidedLink> {
423    let rest = path.strip_prefix(b"/proc/")?;
424    let mut parts = Vec::new();
425    let mut follows = false;
426    for part in rest.split(|byte| *byte == b'/') {
427        match part {
428            b"" | b"." => follows = !parts.is_empty(),
429            b".." => return None,
430            part => {
431                parts.push(part);
432                follows = false;
433            }
434        }
435    }
436    if follows {
437        // `self`, `thread-self` and `net` name directories; `mounts` and the
438        // namespace links name files.
439        return match decided_procfs_link_parts(&parts, pid, tid)? {
440            DecidedLink::Target(_) => Some(DecidedLink::Followed(
441                if matches!(parts.as_slice(), [b"self" | b"thread-self" | b"net"]) {
442                    Errno::EINVAL
443                } else {
444                    Errno::ENOTDIR
445                },
446            )),
447            _ => None,
448        };
449    }
450    decided_procfs_link_parts(&parts, pid, tid)
451}
452
453/// [`decided_procfs_link`] of the components below `/proc` of a spelling
454/// that does not follow its last one.
455fn decided_procfs_link_parts(parts: &[&[u8]], pid: i32, tid: i32) -> Option<DecidedLink> {
456    let pid_name = pid.to_string();
457    let tid_name = tid.to_string();
458    let own_process = |part: &[u8]| part == b"self" || part == pid_name.as_bytes();
459    let own_thread = |part: &[u8]| part == tid_name.as_bytes();
460    let namespace = |parts: &[&[u8]]| {
461        let spelled = std::iter::once(b"/proc".as_slice())
462            .chain(parts.iter().copied())
463            .collect::<Vec<_>>()
464            .join(b"/".as_slice());
465        canonical_namespace_target(Path::new(OsStr::from_bytes(&spelled)))
466            .map(|target| DecidedLink::Target(target.to_vec()))
467    };
468    match parts {
469        [b"self"] => Some(DecidedLink::Target(pid_name.into_bytes())),
470        [b"thread-self"] => Some(DecidedLink::Target(
471            format!("{pid}/task/{tid}").into_bytes(),
472        )),
473        [b"mounts"] => Some(DecidedLink::Target(b"self/mounts".to_vec())),
474        [b"net"] => Some(DecidedLink::Target(b"self/net".to_vec())),
475        [process, b"ns", _] if own_process(process) || *process == b"thread-self" => {
476            namespace(parts)
477        }
478        [process, b"task", thread, b"ns", _] if own_process(process) && own_thread(thread) => {
479            namespace(parts)
480        }
481        [process, b"task", thread, b"fd", fd] if own_process(process) && own_thread(thread) => {
482            decimal_fd(OsStr::from_bytes(fd)).map(DecidedLink::SelfFd)
483        }
484        _ => None,
485    }
486}
487
488/// The procfs directory of guest thread `tid` as the tool reaches it: its
489/// own `/proc/thread-self` where the tool runs in the guest's process
490/// (`tool_shares_guest_descriptor_table`), `/proc/<tid>` where it is a
491/// separate tracer. `None` where guest threads are not host tasks
492/// ([`crate::procfs_inode::tool_can_name_guest_descriptors`]: KVM), after a
493/// guest `chroot` (`changed_root`), and where a tracer's guest has a mount
494/// namespace of its own: the tool would look paths up in another
495/// filesystem view than the guest's.
496pub(crate) fn guest_task_procfs(
497    backend: &reverie::BackendCapabilities,
498    tid: i32,
499    changed_root: bool,
500) -> Option<PathBuf> {
501    if !crate::procfs_inode::tool_can_name_guest_descriptors(backend) || changed_root {
502        return None;
503    }
504    if backend.tool_shares_guest_descriptor_table {
505        return Some(PathBuf::from("/proc/thread-self"));
506    }
507    let task = PathBuf::from(format!("/proc/{tid}"));
508    // Raw syscalls: in-guest Detcore must not call libc's wrappers
509    // (`crate::util::raw_syscall`).
510    let namespace = |path: &Path| crate::util::raw_stat(path).ok().map(|stat| stat.st_ino);
511    (namespace(&task.join("ns/mnt"))? == namespace(Path::new("/proc/self/ns/mnt"))?).then_some(task)
512}
513
514/// Whether the guest's pathname `path` may name an `exe` link Detcore
515/// could not resolve: its final component is `exe`, or it is empty (a
516/// descriptor for the link itself). The launcher guards look only at these
517/// (`Detcore::refuse_launcher_link`, `Detcore::opened_the_launcher`), so
518/// that a guest's own link or open of any other file is never refused.
519pub(crate) fn exe_link_candidate(path: &Path) -> bool {
520    path.as_os_str().is_empty() || path.file_name() == Some(OsStr::new("exe"))
521}
522
523/// Put back the first `written` bytes of a readlink buffer from `saved`,
524/// read before the kernel wrote it, as far as `saved` reaches.
525fn restore_saved_link_bytes<G: Guest<Detcore<T>>, T: RecordOrReplay>(
526    guest: &mut G,
527    buffer: AddrMut<'_, libc::c_char>,
528    written: usize,
529    saved: Option<&[u8]>,
530) {
531    if let Some(saved) = saved {
532        let end = written.min(saved.len());
533        let _ = guest
534            .memory()
535            .write_exact(buffer.cast::<u8>(), &saved[..end]);
536    }
537}
538
539/// Whose `exe` link a `/proc` spelling names ([`exe_link_subject`]).
540#[derive(Clone, Copy, Debug, PartialEq, Eq)]
541pub(crate) enum ExeLinkSubject {
542    /// The caller's own process: `self`, `thread-self`, its pid, or a thread
543    /// in its `task` directory.
544    Own,
545    /// Another process, by the pid the guest sees.
546    Other(i32),
547}
548
549/// Whose `exe` link the absolute, already resolved spelling `path` names
550/// (callers resolve its directory first, `Detcore::resolve_exe_subject`),
551/// for a caller whose pid, as the guest sees it, is `pid`: `/proc/<p>/exe` and
552/// `/proc/<p>/task/<t>/exe` name process `p` (`self` and `thread-self` the
553/// caller's). Linux reads a thread's link from its process's image, and
554/// answers a thread outside `p` with `ENOENT`, which the kernel decides
555/// here too. `None` for any other path, for a spelling with `..`, and for
556/// one that follows the link (a trailing slash or `.`).
557pub(crate) fn exe_link_subject(path: &[u8], pid: i32) -> Option<ExeLinkSubject> {
558    let rest = path.strip_prefix(b"/proc/")?;
559    if path.ends_with(b"/") || path.ends_with(b"/.") {
560        return None;
561    }
562    let mut parts = Vec::new();
563    for part in rest.split(|byte| *byte == b'/') {
564        match part {
565            b"" | b"." => {}
566            b".." => return None,
567            part => parts.push(part),
568        }
569    }
570    let number = |part: &[u8]| -> Option<i32> {
571        let digits = std::str::from_utf8(part).ok()?;
572        // procfs names tasks without leading zeros.
573        (!digits.starts_with('0') && digits.bytes().all(|byte| byte.is_ascii_digit()))
574            .then(|| digits.parse().ok())?
575    };
576    let process = |part: &[u8]| -> Option<ExeLinkSubject> {
577        if part == b"self" {
578            return Some(ExeLinkSubject::Own);
579        }
580        let process = number(part)?;
581        Some(if process == pid {
582            ExeLinkSubject::Own
583        } else {
584            ExeLinkSubject::Other(process)
585        })
586    };
587    match parts.as_slice() {
588        [b"thread-self", b"exe"] => Some(ExeLinkSubject::Own),
589        [subject, b"exe"] => process(subject),
590        [subject, b"task", thread, b"exe"] => {
591            number(thread)?;
592            process(subject)
593        }
594        _ => None,
595    }
596}
597
598// TODO-HUMAN-REVIEW(PR-1079): Review numeric virtual-self proc-fd path rewriting.
599fn host_self_proc_fd_alias(path: &Path, current_pid: i64) -> Option<PathBuf> {
600    let (Some(subject), fd) = proc_fd_target(path)? else {
601        return None;
602    };
603    (i64::from(subject) == current_pid).then(|| PathBuf::from(format!("/proc/self/fd/{fd}")))
604}
605
606#[derive(Debug, Eq, PartialEq)]
607struct AnonymousProcFdIdentity {
608    kind: &'static str,
609    /// The inode number the link names. Its device is the kernel's pipe or
610    /// socket filesystem ([`anonymous_object_device`]).
611    raw_inode: u64,
612}
613
614/// The host devices of the kernel's pipe and socket filesystems, on which
615/// every `pipe:[N]` or `socket:[N]` link's inode lives. Each is one
616/// kernel-wide superblock, so a pipe and a socket made here show them. A host
617/// inode is identified by device AND number, and a pipe's `fstat` reports this
618/// device, so the identity a link names must carry it too.
619#[derive(Clone, Copy, Debug, Eq, PartialEq)]
620pub(crate) struct AnonymousObjectDevices {
621    pipe: u64,
622    socket: u64,
623}
624
625/// The [`AnonymousObjectDevices`], read once per process, or why they could
626/// not be read. Detcore reads them when it starts in a process
627/// ([`crate::Detcore`]'s `Tool::new`), before any guest syscall, so a guest's
628/// readlink never depends on whether the tracer can make a pipe or socket at
629/// that moment, and keeps the outcome either way: a later call neither retries
630/// nor panics.
631pub(crate) fn anonymous_object_devices() -> &'static Result<AnonymousObjectDevices, String> {
632    static DEVICES: std::sync::OnceLock<Result<AnonymousObjectDevices, String>> =
633        std::sync::OnceLock::new();
634    DEVICES.get_or_init(|| retained_probe_outcome(probe_anonymous_object_devices()))
635}
636
637/// The probe's outcome as Detcore keeps it. Under in-guest LiteInst the probe
638/// runs inside the guest before `main`, so a failure is described without the
639/// C library's errno message (see [`crate::util::describe_io_error`]).
640fn retained_probe_outcome(
641    probe: std::io::Result<AnonymousObjectDevices>,
642) -> Result<AnonymousObjectDevices, String> {
643    probe.map_err(|error| crate::util::describe_io_error(&error))
644}
645
646fn probe_anonymous_object_devices() -> std::io::Result<AnonymousObjectDevices> {
647    use crate::util::raw_syscall;
648    use crate::util::raw_zero_result;
649    // Raw syscalls (see crate::util::raw_syscall): Detcore::new runs this
650    // inside the guest under in-guest LiteInst.
651    let close = |fds: [i32; 2]| {
652        for fd in fds {
653            unsafe { raw_syscall(libc::SYS_close, [fd as u64, 0, 0, 0, 0, 0]) };
654        }
655    };
656    let device_of = |fd: i32| -> std::io::Result<u64> {
657        let mut metadata: libc::stat = unsafe { std::mem::zeroed() };
658        raw_zero_result(unsafe {
659            raw_syscall(
660                libc::SYS_fstat,
661                [fd as u64, (&raw mut metadata) as u64, 0, 0, 0, 0],
662            )
663        })?;
664        Ok(metadata.st_dev)
665    };
666    let mut pipe = [0_i32; 2];
667    raw_zero_result(unsafe {
668        raw_syscall(
669            libc::SYS_pipe2,
670            [pipe.as_mut_ptr() as u64, libc::O_CLOEXEC as u64, 0, 0, 0, 0],
671        )
672    })?;
673    let pipe_device = device_of(pipe[0]);
674    close(pipe);
675    let mut sockets = [0_i32; 2];
676    raw_zero_result(unsafe {
677        raw_syscall(
678            libc::SYS_socketpair,
679            [
680                libc::AF_UNIX as u64,
681                (libc::SOCK_DGRAM | libc::SOCK_CLOEXEC) as u64,
682                0,
683                sockets.as_mut_ptr() as u64,
684                0,
685                0,
686            ],
687        )
688    })?;
689    let socket_device = device_of(sockets[0]);
690    close(sockets);
691    Ok(AnonymousObjectDevices {
692        pipe: pipe_device?,
693        socket: socket_device?,
694    })
695}
696
697/// The device of a `kind` ("pipe" or "socket") link's inode, from the
698/// devices read at start (`devices`). When they could not be read, this is a
699/// tool error, not an errno: Detcore cannot give the link a faithful identity,
700/// so the run fails as an infrastructure failure through the backend's own
701/// failure handling, rather than a link identity getting an invented device or
702/// a guest getting an error Linux would not return.
703fn anonymous_object_device(
704    devices: &Result<AnonymousObjectDevices, String>,
705    kind: &str,
706) -> Result<u64, Error> {
707    let devices = devices.as_ref().map_err(|error| {
708        Error::Tool(anyhow::anyhow!(
709            "Detcore could not read the pipe and socket filesystem devices when it started \
710             ({error}), so it cannot identify the {kind} a /proc fd link names"
711        ))
712    })?;
713    Ok(match kind {
714        "pipe" => devices.pipe,
715        "socket" => devices.socket,
716        _ => unreachable!("anonymous_proc_fd_identity names only pipes and sockets, not {kind}"),
717    })
718}
719
720// Long enough for `socket:[` + every decimal u64 inode + `]`.
721/// Room for a whole pipe or socket link, and for the link of a placeholder
722/// for a procfs file Detcore renders (`crate::procfs::placeholder_link_path`).
723const ANONYMOUS_PROC_FD_TARGET_CAPACITY: usize = crate::procfs::PLACEHOLDER_LINK_CAPACITY;
724
725fn needs_anonymous_proc_fd_scratch(buffer_present: bool, buffer_len: usize) -> bool {
726    buffer_present && buffer_len != 0 && buffer_len < ANONYMOUS_PROC_FD_TARGET_CAPACITY
727}
728
729/// Recognize only a complete kernel pipe/socket symlink target.
730fn anonymous_proc_fd_identity(target: &[u8]) -> Option<AnonymousProcFdIdentity> {
731    for (kind, prefix) in [
732        ("pipe", b"pipe:[".as_slice()),
733        ("socket", b"socket:[".as_slice()),
734    ] {
735        let Some(digits) = target
736            .strip_prefix(prefix)
737            .and_then(|rest| rest.strip_suffix(b"]"))
738        else {
739            continue;
740        };
741        if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {
742            continue;
743        }
744        let raw_inode = std::str::from_utf8(digits).ok()?.parse().ok()?;
745        return Some(AnonymousProcFdIdentity { kind, raw_inode });
746    }
747    None
748}
749
750/// Match a raw identity against cached current-process inherited-stdio identities.
751/// Callers exclude ordinary replacement objects before filling this array.
752///
753/// When stdio descriptors alias, the lowest one wins, as in the maps
754/// sanitizer's `stdio_by_raw_inode` table. Detcore gives all three inherited
755/// descriptors the stat of its own stdin, so they alias until the guest
756/// replaces them: a link to that object is a link to fd 0, and must read as
757/// the `pipe:[1000]` a readlink of fd 0 returns.
758fn deterministic_stdio_inode_for_raw(
759    raw_inode: RawInode,
760    stdio_raw_inodes: &[Option<RawInode>; 3],
761) -> Option<DetInode> {
762    let fd = stdio_raw_inodes
763        .iter()
764        .position(|cached| *cached == Some(raw_inode))?;
765    deterministic_stdio_inode(fd as i32)
766}
767
768fn canonical_anonymous_proc_fd_target(
769    identity: &AnonymousProcFdIdentity,
770    inode: DetInode,
771    buffer_len: usize,
772) -> Vec<u8> {
773    let mut target = format!("{}:[{}]", identity.kind, inode.as_raw()).into_bytes();
774    target.truncate(buffer_len);
775    target
776}
777
778impl<T: RecordOrReplay> Detcore<T> {
779    async fn canonicalize_other_proc_fd_target<G>(
780        &self,
781        guest: &mut G,
782        link: (i32, Option<PathPtr<'_>>),
783        raw_target: &[u8],
784        buffer: Option<AddrMut<'_, libc::c_char>>,
785        buffer_len: usize,
786        saved: Option<&[u8]>,
787    ) -> Result<Option<i64>, Error>
788    where
789        G: Guest<Self>,
790    {
791        if let Some(path) =
792            crate::procfs::placeholder_link_path(raw_target, self.rendered_files(guest))
793            && self.placeholder_link_confirmed(guest, link).await
794        {
795            // Another process's link to a procfs file Detcore renders names
796            // the file, as Linux's does.
797            let link = std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str());
798            let written = link.len().min(buffer_len);
799            let buffer = buffer.ok_or(Errno::EFAULT)?;
800            guest
801                .memory()
802                .write_exact(buffer.cast(), &link[..written])?;
803            restore_link_tail(guest, buffer, written, raw_target.len(), saved)?;
804            return Ok(Some(written as i64));
805        }
806        let Some(identity) = anonymous_proc_fd_identity(raw_target) else {
807            return Ok(None);
808        };
809        let mut stdio_raw_inodes = [None; 3];
810        for fd in libc::STDIN_FILENO..=libc::STDERR_FILENO {
811            stdio_raw_inodes[fd as usize] = guest
812                .thread_state()
813                .with_detfd(fd, |detfd| {
814                    deterministic_stdio_inode_for_resource(fd, detfd.resource())?;
815                    detfd.stat().map(|stat| stat.raw_inode())
816                })
817                .ok()
818                .flatten();
819        }
820        let raw_inode = RawInode::new(
821            anonymous_object_device(anonymous_object_devices(), identity.kind)?,
822            identity.raw_inode,
823        );
824        // Every link sends its numbering request, and a stdio match only
825        // chooses the rendering afterwards, as `/proc/*/maps` does: whether
826        // the raw identity matches stdio is host identity, which must not
827        // decide how many inode numbers the call consumes
828        // (<https://github.com/rrnewton/hermit/issues/2897>).
829        let pooled = determinize_inode(guest, raw_inode).await.0;
830        let inode =
831            deterministic_stdio_inode_for_raw(raw_inode, &stdio_raw_inodes).unwrap_or(pooled);
832        let target = canonical_anonymous_proc_fd_target(&identity, inode, buffer_len);
833        let buffer = buffer.ok_or(Errno::EFAULT)?;
834        guest.memory().write_exact(buffer.cast(), &target)?;
835        // The raw link's longer inode digits must not stay behind the
836        // canonical one: Linux writes only the link.
837        restore_link_tail(guest, buffer, target.len(), raw_target.len(), saved)?;
838        Ok(Some(target.len() as i64))
839    }
840
841    /// Canonicalize a pipe/socket link belonging to another virtual process.
842    /// The target descriptor is not in the caller's table, so its raw readlink
843    /// bytes are the only safe identity evidence available here.
844    async fn canonicalize_other_proc_fd_readlink<G>(
845        &self,
846        guest: &mut G,
847        link: (i32, Option<PathPtr<'_>>),
848        buffer: Option<AddrMut<'_, libc::c_char>>,
849        buffer_len: usize,
850        result: i64,
851        saved: Option<&[u8]>,
852    ) -> Result<i64, Error>
853    where
854        G: Guest<Self>,
855    {
856        let buffer = buffer.expect("a successful readlink requires a non-null buffer");
857        let observed_len = usize::try_from(result)
858            .expect("a positive readlink result must fit usize")
859            .min(buffer_len);
860        let mut observed = vec![0; observed_len];
861        guest.memory().read_exact(buffer.cast(), &mut observed)?;
862        Ok(self
863            .canonicalize_other_proc_fd_target(
864                guest,
865                link,
866                &observed,
867                Some(buffer),
868                buffer_len,
869                saved,
870            )
871            .await?
872            .unwrap_or(result))
873    }
874
875    async fn canonicalize_namespace_readlink_result<G>(
876        &self,
877        guest: &mut G,
878        path: PathBuf,
879        buffer: Option<AddrMut<'_, libc::c_char>>,
880        buffer_len: usize,
881        result: i64,
882    ) -> Result<i64, Error>
883    where
884        G: Guest<Self>,
885    {
886        if result <= 0 {
887            return Ok(result);
888        }
889
890        let target = if let Some(target) = canonical_namespace_target(&path) {
891            target.to_vec()
892        } else if let Some((subject, fd)) = proc_fd_target(&path) {
893            if let Some(subject) = subject {
894                let current_pid = self.guest_visible_own_pid(guest).await?;
895                if current_pid != i64::from(subject) {
896                    return self
897                        .canonicalize_other_proc_fd_readlink(
898                            guest,
899                            (libc::AT_FDCWD, None),
900                            buffer,
901                            buffer_len,
902                            result,
903                            None,
904                        )
905                        .await;
906                }
907            }
908
909            let stat = self.inject_fstat(guest, fd).await?;
910            let kind = match stat.st_mode & libc::S_IFMT {
911                libc::S_IFIFO => "pipe",
912                libc::S_IFSOCK => "socket",
913                _ => return Ok(result),
914            };
915            let inode_override = guest
916                .thread_state()
917                .with_detfd(fd, |detfd| {
918                    deterministic_stdio_inode_for_resource(fd, detfd.resource())
919                })
920                .ok()
921                .flatten();
922            let inode = match inode_override {
923                Some(inode) => inode,
924                None => {
925                    determinize_inode(guest, RawInode::new(stat.st_dev, stat.st_ino))
926                        .await
927                        .0
928                }
929            };
930            format!("{kind}:[{inode}]").into_bytes()
931        } else {
932            return Ok(result);
933        };
934
935        let written = target.len().min(buffer_len);
936        let buffer = buffer.expect("a successful readlink requires a non-null buffer");
937        guest
938            .memory()
939            .write_exact(buffer.cast(), &target[..written])?;
940        Ok(written as i64)
941    }
942    async fn write_other_proc_fd_target<G>(
943        &self,
944        guest: &mut G,
945        link: (i32, Option<PathPtr<'_>>),
946        raw_target: &[u8],
947        buffer: Option<AddrMut<'_, libc::c_char>>,
948        buffer_len: usize,
949    ) -> Result<i64, Error>
950    where
951        G: Guest<Self>,
952    {
953        if let Some(result) = self
954            .canonicalize_other_proc_fd_target(guest, link, raw_target, buffer, buffer_len, None)
955            .await?
956        {
957            return Ok(result);
958        }
959        let written = raw_target.len().min(buffer_len);
960        let buffer = buffer.ok_or(Errno::EFAULT)?;
961        guest
962            .memory()
963            .write_exact(buffer.cast(), &raw_target[..written])?;
964        Ok(written as i64)
965    }
966
967    async fn finish_other_proc_fd_readlink<G>(
968        &self,
969        guest: &mut G,
970        call: syscalls::Readlink,
971    ) -> Result<i64, Error>
972    where
973        G: Guest<Self>,
974    {
975        let link = (libc::AT_FDCWD, call.path());
976        let buffer = call.buf();
977        let buffer_len = call.bufsize();
978        if !needs_anonymous_proc_fd_scratch(buffer.is_some(), buffer_len) {
979            let saved = saved_link_bytes(guest, buffer, buffer_len);
980            let result = self.record_or_replay(guest, call).await?;
981            if result <= 0 {
982                return Ok(result);
983            }
984            return self
985                .canonicalize_other_proc_fd_readlink(
986                    guest,
987                    link,
988                    buffer,
989                    buffer_len,
990                    result,
991                    saved.as_deref(),
992                )
993                .await;
994        }
995
996        let mut stack = guest.stack().await;
997        let scratch = stack
998            .reserve::<[u8; ANONYMOUS_PROC_FD_TARGET_CAPACITY]>()
999            .cast::<libc::c_char>();
1000        let guard = stack.commit()?;
1001        let physical_call = call
1002            .with_buf(Some(scratch))
1003            .with_bufsize(ANONYMOUS_PROC_FD_TARGET_CAPACITY);
1004        let result = self.record_or_replay(guest, physical_call).await?;
1005        let length = usize::try_from(result)
1006            .expect("a successful readlink result must fit usize")
1007            .min(ANONYMOUS_PROC_FD_TARGET_CAPACITY);
1008        let mut raw_target = vec![0; length];
1009        guest.memory().read_exact(scratch.cast(), &mut raw_target)?;
1010        drop(guard);
1011        self.write_other_proc_fd_target(guest, link, &raw_target, buffer, buffer_len)
1012            .await
1013    }
1014
1015    async fn finish_other_proc_fd_readlinkat<G>(
1016        &self,
1017        guest: &mut G,
1018        call: syscalls::Readlinkat,
1019    ) -> Result<i64, Error>
1020    where
1021        G: Guest<Self>,
1022    {
1023        let link = (call.dirfd(), call.path());
1024        let buffer = call.buf();
1025        let buffer_len = call.buf_len();
1026        if !needs_anonymous_proc_fd_scratch(buffer.is_some(), buffer_len) {
1027            let saved = saved_link_bytes(guest, buffer, buffer_len);
1028            let result = self.record_or_replay(guest, call).await?;
1029            if result <= 0 {
1030                return Ok(result);
1031            }
1032            return self
1033                .canonicalize_other_proc_fd_readlink(
1034                    guest,
1035                    link,
1036                    buffer,
1037                    buffer_len,
1038                    result,
1039                    saved.as_deref(),
1040                )
1041                .await;
1042        }
1043
1044        let mut stack = guest.stack().await;
1045        let scratch = stack
1046            .reserve::<[u8; ANONYMOUS_PROC_FD_TARGET_CAPACITY]>()
1047            .cast::<libc::c_char>();
1048        let guard = stack.commit()?;
1049        let physical_call = call
1050            .with_buf(Some(scratch))
1051            .with_buf_len(ANONYMOUS_PROC_FD_TARGET_CAPACITY);
1052        let result = self.record_or_replay(guest, physical_call).await?;
1053        let length = usize::try_from(result)
1054            .expect("a successful readlinkat result must fit usize")
1055            .min(ANONYMOUS_PROC_FD_TARGET_CAPACITY);
1056        let mut raw_target = vec![0; length];
1057        guest.memory().read_exact(scratch.cast(), &mut raw_target)?;
1058        drop(guard);
1059        self.write_other_proc_fd_target(guest, link, &raw_target, buffer, buffer_len)
1060            .await
1061    }
1062
1063    /// The rendered procfs file that the descriptor link `path` (absolute)
1064    /// names a placeholder for, read whole into scratch space.
1065    async fn placeholder_behind_link<G: Guest<Self>>(
1066        &self,
1067        guest: &mut G,
1068        path: &Path,
1069    ) -> Result<Option<&'static Path>, Error> {
1070        const PATH_CAPACITY: usize = 64;
1071        let bytes = path.as_os_str().as_bytes();
1072        if bytes.len() >= PATH_CAPACITY {
1073            return Ok(None);
1074        }
1075        let mut path_buffer = [0_u8; PATH_CAPACITY];
1076        path_buffer[..bytes.len()].copy_from_slice(bytes);
1077        let mut stack = guest.stack().await;
1078        let path_address = stack.push(path_buffer).cast::<libc::c_char>();
1079        let scratch = stack
1080            .reserve::<[u8; ANONYMOUS_PROC_FD_TARGET_CAPACITY]>()
1081            .cast::<libc::c_char>();
1082        let guard = stack.commit()?;
1083        let length = guest
1084            .inject(
1085                syscalls::Readlinkat::new()
1086                    .with_dirfd(libc::AT_FDCWD)
1087                    .with_path(PathPtr::from_ptr(
1088                        path_address.as_raw() as *const libc::c_char
1089                    ))
1090                    .with_buf(Some(scratch))
1091                    .with_buf_len(ANONYMOUS_PROC_FD_TARGET_CAPACITY),
1092            )
1093            .await;
1094        let rendered = match length {
1095            Ok(length) => {
1096                let mut target = vec![0; (length as usize).min(ANONYMOUS_PROC_FD_TARGET_CAPACITY)];
1097                guest.memory().read_exact(scratch.cast(), &mut target)?;
1098                crate::procfs::placeholder_link_path(&target, self.rendered_files(guest))
1099            }
1100            Err(_) => None,
1101        };
1102        drop(guard);
1103        Ok(rendered)
1104    }
1105
1106    // AUTONOMOUS-BOT-IMPLEMENTED
1107    // TODO-HUMAN-REVIEW(#877)
1108    async fn finish_namespace_readlink<G, S>(
1109        &self,
1110        guest: &mut G,
1111        link: (i32, Option<PathPtr<'_>>),
1112        path: PathBuf,
1113        buffer: Option<AddrMut<'_, libc::c_char>>,
1114        buffer_len: usize,
1115        syscall: S,
1116    ) -> Result<i64, Error>
1117    where
1118        G: Guest<Self>,
1119        S: Into<Syscall>,
1120    {
1121        let saved = saved_link_bytes(guest, buffer, buffer_len);
1122        let result = self.record_or_replay(guest, syscall).await?;
1123        self.finish_namespace_readlink_result(
1124            guest,
1125            link,
1126            path,
1127            buffer,
1128            buffer_len,
1129            (result, saved.as_deref()),
1130        )
1131        .await
1132    }
1133
1134    /// [`Self::finish_namespace_readlink`] after the call, which returned
1135    /// `result` over a buffer that held `saved` before it.
1136    async fn finish_namespace_readlink_result<G>(
1137        &self,
1138        guest: &mut G,
1139        link: (i32, Option<PathPtr<'_>>),
1140        path: PathBuf,
1141        buffer: Option<AddrMut<'_, libc::c_char>>,
1142        buffer_len: usize,
1143        (result, saved): (i64, Option<&[u8]>),
1144    ) -> Result<i64, Error>
1145    where
1146        G: Guest<Self>,
1147    {
1148        // A link that filled a buffer too short for a placeholder's link,
1149        // spelled as a task's descriptor link (`task/<tid>/fd/N`) or starting
1150        // as a placeholder's link does: the whole link shows whether it was
1151        // one.
1152        let filled_like_a_placeholder = match (buffer, usize::try_from(result)) {
1153            (Some(address), Ok(length)) if length == buffer_len => {
1154                let prefix = b"/memfd:hermit-procfs:";
1155                let mut head = vec![0; length.min(prefix.len())];
1156                guest
1157                    .memory()
1158                    .read_exact(address.cast::<u8>(), &mut head)
1159                    .is_ok()
1160                    && prefix.starts_with(&head)
1161            }
1162            _ => false,
1163        };
1164        let result = match usize::try_from(result) {
1165            Ok(length)
1166                if length == buffer_len
1167                    && needs_anonymous_proc_fd_scratch(buffer.is_some(), buffer_len)
1168                    && !self.cfg.recordreplay_modes
1169                    && (names_task_descriptor_link(&path) || filled_like_a_placeholder) =>
1170            {
1171                match self.placeholder_behind_link(guest, &path).await? {
1172                    Some(rendered) if self.placeholder_link_confirmed(guest, link).await => {
1173                        let link = rendered.as_os_str().as_bytes();
1174                        let written = link.len().min(buffer_len);
1175                        let address = buffer.ok_or(Errno::EFAULT)?;
1176                        guest
1177                            .memory()
1178                            .write_exact(address.cast(), &link[..written])?;
1179                        restore_link_tail(guest, address, written, length, saved)?;
1180                        written as i64
1181                    }
1182                    _ => result,
1183                }
1184            }
1185            _ => {
1186                self.rewrite_placeholder_link(guest, link, buffer, buffer_len, result, saved)
1187                    .await?
1188            }
1189        };
1190        self.canonicalize_namespace_readlink_result(guest, path, buffer, buffer_len, result)
1191            .await
1192    }
1193
1194    /// The calling process's pid as the guest sees it, which a `/proc/<pid>`
1195    /// spelling names: Detcore's pid for the process outside a nested PID
1196    /// namespace ([`Self::procfs_caller_ids`]), the kernel's answer inside
1197    /// one.
1198    pub(crate) async fn guest_visible_own_pid<G: Guest<Self>>(
1199        &self,
1200        guest: &mut G,
1201    ) -> Result<i64, Error> {
1202        match self.procfs_caller_ids(guest) {
1203            Some((pid, _)) => Ok(i64::from(pid)),
1204            None => Ok(guest.inject(syscalls::Getpid::new()).await?),
1205        }
1206    }
1207
1208    /// The calling thread's pid and tid as the guest's `/proc` spellings
1209    /// name them (`/proc/<pid>/...`, `/proc/<pid>/task/<tid>/...`): Detcore's
1210    /// pid for the thread's process and its tid. This is the one rule for
1211    /// whether such a spelling is the caller's own, which every check that
1212    /// recognizes one uses (the descriptor-link recording of an open, and
1213    /// [`Self::guest_visible_own_pid`]'s callers, such as
1214    /// `rendered_procfs_at`), so that they cannot disagree.
1215    ///
1216    /// They are the numbers the guest's own `getpid` and `gettid` return, on
1217    /// every backend: measured on ptrace, DBT and KVM for the root process,
1218    /// one of its threads and its first fork child, an injected `getpid` and
1219    /// `gettid` returned exactly these. And they are the numbers procfs, as
1220    /// the guest reaches it, uses for them: ptrace's and KVM's procfs number
1221    /// processes as Detcore does, and DBT, whose kernel numbers them
1222    /// otherwise, spells each guest number with the kernel's before the
1223    /// kernel looks the path up (`Detcore::translates_procfs_numbers`;
1224    /// DBT refuses record and replay, the one mode that would leave its
1225    /// numbers untranslated). So nothing is injected to learn them.
1226    ///
1227    /// `None` in a nested PID namespace, whose numbers are its own; a caller
1228    /// that needs the namespace's pid there asks the kernel. Detcore's pid is
1229    /// the thread's own record of it, as at thread exit: a DBT fork child
1230    /// keeps its parent's tool.
1231    pub(crate) fn procfs_caller_ids<G: Guest<Self>>(&self, guest: &G) -> Option<(i32, i32)> {
1232        let state = guest.thread_state();
1233        (!state.nested_pid_namespace)
1234            .then(|| (self.own_detpid(guest).as_raw(), state.dettid.as_raw()))
1235    }
1236
1237    /// The calling thread's procfs directory as the tool reaches it
1238    /// ([`guest_task_procfs`]).
1239    pub(crate) fn guest_task_directory<G: Guest<Self>>(&self, guest: &G) -> Option<PathBuf> {
1240        guest_task_procfs(
1241            &self.cfg.backend,
1242            guest.tid().as_raw(),
1243            guest
1244                .thread_state()
1245                .changed_root
1246                .load(std::sync::atomic::Ordering::SeqCst),
1247        )
1248    }
1249
1250    /// The calling thread's root directory as the tool sees it, read from its
1251    /// procfs directory ([`Self::guest_task_directory`]).
1252    pub(crate) fn guest_root<G: Guest<Self>>(&self, guest: &G) -> Option<PathBuf> {
1253        crate::util::raw_read_link(&self.guest_task_directory(guest)?.join("root")).ok()
1254    }
1255
1256    /// The absolute spelling of an `exe` link the caller names by `path`
1257    /// from `dirfd`, read through its own procfs directory: a relative path
1258    /// joined to the directory the kernel holds for its working directory
1259    /// or descriptor, which names the process a descriptor on `/proc/self`
1260    /// was opened for (a child that inherited it reads its parent's link).
1261    /// `None` where the directory cannot be read, and for an empty path.
1262    pub(crate) fn exe_link_spelling<G: Guest<Self>>(
1263        &self,
1264        guest: &G,
1265        dirfd: i32,
1266        path: &Path,
1267    ) -> Option<PathBuf> {
1268        if path.is_absolute() {
1269            return Some(path.to_path_buf());
1270        }
1271        if path.as_os_str().is_empty() {
1272            return None;
1273        }
1274        let task = self.guest_task_directory(guest)?;
1275        let directory = if dirfd == libc::AT_FDCWD {
1276            task.join("cwd")
1277        } else {
1278            task.join("fd").join(dirfd.to_string())
1279        };
1280        let directory = std::fs::read_link(directory).ok()?;
1281        let root = std::fs::read_link(task.join("root")).ok()?;
1282        Some(
1283            Path::new("/")
1284                .join(directory.strip_prefix(&root).ok()?)
1285                .join(path),
1286        )
1287    }
1288
1289    /// Whose `exe` link the absolute spelling `spelled` reaches, decided the
1290    /// way the kernel looks it up: its directory resolved in the guest's
1291    /// view, so `self`, `thread-self`, `..` and symbolic links within it name
1292    /// the process they lead to, and with `follow` (an open or an exec, which
1293    /// follow the final link) a symbolic link in the final component followed
1294    /// too. `None` for any other file, and where the tool cannot read the
1295    /// guest's filesystem view ([`Self::guest_task_directory`]).
1296    pub(crate) fn resolve_exe_subject<G: Guest<Self>>(
1297        &self,
1298        guest: &G,
1299        spelled: &Path,
1300        follow: bool,
1301    ) -> Option<ExeLinkSubject> {
1302        let root = self.guest_root(guest)?;
1303        let inside = |path: &Path| -> Option<PathBuf> {
1304            Some(Path::new("/").join(path.strip_prefix(&root).ok()?))
1305        };
1306        // Where the tool reads the guest's procfs by number rather than
1307        // through its own `thread-self` (`guest_task_procfs`), name the
1308        // guest's directory by its pid: a tracer's own `self` and
1309        // `thread-self` are not the guest's. In-guest tools take the same
1310        // path, where the numbered directory is their own.
1311        let numbered_procfs = !self.cfg.backend.tool_shares_guest_descriptor_table;
1312        let spelled = if numbered_procfs {
1313            let (pid, tid) = (guest.pid().as_raw(), guest.tid().as_raw());
1314            let mut parts = spelled.components();
1315            match (parts.next(), parts.next(), parts.next()) {
1316                (Some(Component::RootDir), Some(proc), Some(own)) if proc.as_os_str() == "proc" => {
1317                    let own = match own.as_os_str().to_str() {
1318                        Some("self") => PathBuf::from(format!("/proc/{pid}")),
1319                        Some("thread-self") => PathBuf::from(format!("/proc/{pid}/task/{tid}")),
1320                        _ => spelled.to_path_buf(),
1321                    };
1322                    if own.as_path() == spelled {
1323                        own
1324                    } else {
1325                        own.join(parts.as_path())
1326                    }
1327                }
1328                _ => spelled.to_path_buf(),
1329            }
1330        } else {
1331            spelled.to_path_buf()
1332        };
1333        let spelled = spelled.as_path();
1334        // The caller's pid as its procfs numbers it: a tracer's view of it,
1335        // Detcore's, or in a nested PID namespace the namespace's, read from
1336        // its own `thread-self` (the tool shares the guest's process there).
1337        let pid = if numbered_procfs {
1338            guest.pid().as_raw()
1339        } else if guest.thread_state().nested_pid_namespace {
1340            let own = crate::util::canonicalize(&root.join("proc/thread-self")).ok()?;
1341            let own = inside(&own)?;
1342            let mut parts = own.components().skip(2);
1343            parts.next()?.as_os_str().to_str()?.parse().ok()?
1344        } else {
1345            self.own_detpid(guest).as_raw()
1346        };
1347        let mut spelled = spelled.to_path_buf();
1348        // As many links as the kernel follows (`MAXSYMLINKS`).
1349        for _ in 0..40 {
1350            let name = spelled.file_name()?.to_owned();
1351            let parent = spelled.parent()?;
1352            let directory = inside(
1353                &crate::util::canonicalize(&root.join(parent.strip_prefix("/").ok()?)).ok()?,
1354            )?;
1355            let candidate = directory.join(&name);
1356            if let Some(subject) = exe_link_subject(candidate.as_os_str().as_bytes(), pid) {
1357                return Some(subject);
1358            }
1359            if !follow {
1360                return None;
1361            }
1362            let link = root.join(candidate.strip_prefix("/").ok()?);
1363            if !std::fs::symlink_metadata(&link)
1364                .ok()?
1365                .file_type()
1366                .is_symlink()
1367            {
1368                return None;
1369            }
1370            spelled = directory.join(std::fs::read_link(&link).ok()?);
1371        }
1372        None
1373    }
1374
1375    /// How Detcore answers an `exe` link the caller names by `path` from
1376    /// `dirfd`: in a run whose launch exec'd a launcher in the guest's place
1377    /// ([`crate::LaunchImage::launcher`]: SaBRe's loader, DynamoRIO's
1378    /// library), where the kernel's link names the launcher instead of the
1379    /// guest's image,
1380    /// `Some(record)`: the image Detcore recorded at the exec of the process
1381    /// the link reaches ([`crate::exec_record`]), `None` when it has none to
1382    /// give, which the caller refuses by name rather than let the kernel name
1383    /// the launcher. `None` outside such a run and for any other path: the
1384    /// kernel's answer stands, as on every backend whose kernel exec'd the
1385    /// guest itself. `follow` as [`Self::resolve_exe_subject`].
1386    pub(crate) async fn launched_exe<G: Guest<Self>>(
1387        &self,
1388        guest: &mut G,
1389        (dirfd, path): (i32, &Path),
1390        follow: bool,
1391    ) -> Option<Option<Arc<crate::exec_record::ExecRecord>>> {
1392        self.cfg.launch_image.as_ref()?.launcher.as_ref()?;
1393        let spelled = self.exe_link_spelling(guest, dirfd, path)?;
1394        let subject = self.resolve_exe_subject(guest, &spelled, follow)?;
1395        if guest.thread_state().nested_pid_namespace && matches!(subject, ExeLinkSubject::Other(_))
1396        {
1397            // Its pids are not Detcore's.
1398            return Some(None);
1399        }
1400        Some(match subject {
1401            ExeLinkSubject::Own => guest.thread_state().exe.clone(),
1402            ExeLinkSubject::Other(pid) => {
1403                crate::tool_global::process_image(guest, crate::types::DetPid::from_raw(pid))
1404                    .await
1405                    .map(Arc::new)
1406            }
1407        })
1408    }
1409
1410    /// Refuse, by name, an `exe` link Detcore cannot answer faithfully in a
1411    /// run whose kernel names the launcher (`Self::launched_exe`): without a
1412    /// record, or for an image no longer at its path, whose current name
1413    /// (or " (deleted)") only the kernel's link to the image could give.
1414    pub(crate) async fn refuse_launched_exe<G: Guest<Self>>(
1415        &self,
1416        guest: &mut G,
1417        sysno: reverie::syscalls::Sysno,
1418        exe: Option<&crate::exec_record::ExecRecord>,
1419    ) -> Result<i64, Error> {
1420        let reason = match exe {
1421            None => "unsupported: a /proc/<pid>/exe link of an image Detcore has no record of, \
1422                     where the kernel's link names the launcher"
1423                .to_owned(),
1424            Some(exe) => format!(
1425                "unsupported: a /proc/<pid>/exe link of {:?}, no longer at its path, \
1426                 where the kernel's link names the launcher",
1427                exe.exe
1428            ),
1429        };
1430        self.refuse_launched_exe_because(guest, sysno, reason).await
1431    }
1432
1433    /// [`Self::refuse_launched_exe`], for `reason`.
1434    pub(crate) async fn refuse_launched_exe_because<G: Guest<Self>>(
1435        &self,
1436        guest: &mut G,
1437        sysno: reverie::syscalls::Sysno,
1438        reason: String,
1439    ) -> Result<i64, Error> {
1440        tracing::error!("[tid {}] {}", guest.tid(), reason);
1441        // Said here too: a launched run's launcher does not print the reason
1442        // the coordinator records.
1443        let _ = std::io::Write::write_fmt(
1444            &mut crate::util::RetryingStderr,
1445            format_args!("hermit: {reason}\n"),
1446        );
1447        self.refuse_unserviceable_operation_because(guest, sysno, Errno::EOPNOTSUPP, &reason)
1448            .await
1449    }
1450
1451    /// Refuse, by name, a readlink of a possible `exe` link at `path`
1452    /// ([`exe_link_candidate`]) whose answer, `result` bytes in `buffer`,
1453    /// is the launcher, in a run that declared one
1454    /// ([`crate::LaunchImage::launcher`]): a link Detcore could not resolve
1455    /// (after a guest `chroot`, through a descriptor for the link itself)
1456    /// whose kernel answer would be the launcher in the guest's image's
1457    /// place. The answer must be the launcher's whole path; one the kernel
1458    /// truncated to the buffer is read again whole (`link`, the guest's
1459    /// lookup) before it counts. The buffer gets back the bytes in `saved`
1460    /// before the refusal, so a run that lets the guest go on sees it
1461    /// untouched. Every other result passes through.
1462    async fn refuse_launcher_link<G: Guest<Self>>(
1463        &self,
1464        guest: &mut G,
1465        (sysno, path, link): (reverie::syscalls::Sysno, &Path, (i32, Option<PathPtr<'_>>)),
1466        (buffer, buffer_len): (Option<AddrMut<'_, libc::c_char>>, usize),
1467        result: i64,
1468        saved: Option<&[u8]>,
1469    ) -> Result<i64, Error> {
1470        let (Some(launcher), Some(buffer), Ok(len)) =
1471            (self.declared_launcher(), buffer, usize::try_from(result))
1472        else {
1473            return Ok(result);
1474        };
1475        if len == 0 || !exe_link_candidate(path) {
1476            return Ok(result);
1477        }
1478        let launcher = launcher.as_os_str().as_bytes();
1479        let truncated = len == buffer_len && len < launcher.len();
1480        if len > launcher.len() || (len < launcher.len() && !truncated) {
1481            return Ok(result);
1482        }
1483        let mut answer = vec![0; len];
1484        if guest
1485            .memory()
1486            .read_exact(buffer.cast::<u8>(), &mut answer)
1487            .is_err()
1488            || !launcher.starts_with(&answer)
1489        {
1490            return Ok(result);
1491        }
1492        if truncated && self.whole_link(guest, link).await.as_deref() != Some(launcher) {
1493            return Ok(result);
1494        }
1495        restore_saved_link_bytes(guest, buffer, len, saved);
1496        self.refuse_launched_exe(guest, sysno, None).await
1497    }
1498
1499    /// The whole target of the link the guest names by `link` (its `dirfd`
1500    /// and pathname), read again by the kernel into a buffer that holds any
1501    /// path Linux renders. `None` where it cannot be read so, or the guest
1502    /// stack cannot hold the buffer.
1503    async fn whole_link<G: Guest<Self>>(
1504        &self,
1505        guest: &mut G,
1506        (dirfd, path): (i32, Option<PathPtr<'_>>),
1507    ) -> Option<Vec<u8>> {
1508        const CAPACITY: usize = libc::PATH_MAX as usize;
1509        let mut stack = guest.stack().await;
1510        if stack.capacity() < CAPACITY {
1511            return None;
1512        }
1513        let scratch = stack.reserve::<[u8; CAPACITY]>().cast::<libc::c_char>();
1514        let guard = stack.commit().ok()?;
1515        let call = syscalls::Readlinkat::new()
1516            .with_dirfd(dirfd)
1517            .with_path(path)
1518            .with_buf(Some(scratch))
1519            .with_buf_len(CAPACITY);
1520        let length = usize::try_from(guest.inject(call).await.ok()?).ok()?;
1521        let mut target = vec![0; length.min(CAPACITY)];
1522        let read = guest.memory().read_exact(scratch.cast(), &mut target);
1523        drop(guard);
1524        read.ok().map(|()| target)
1525    }
1526
1527    /// The launcher a launched run declared ([`crate::LaunchImage::launcher`]),
1528    /// canonical.
1529    pub(crate) fn declared_launcher(&self) -> Option<PathBuf> {
1530        let launcher = self.cfg.launch_image.as_ref()?.launcher.as_ref()?;
1531        Some(crate::util::canonicalize(launcher).unwrap_or_else(|_| launcher.clone()))
1532    }
1533
1534    /// Answer a readlink of an `exe` link from `exe` (`Self::launched_exe`)
1535    /// after the kernel answered the guest's call, with `result`: the kernel
1536    /// decides whether the link is there and every error (an exited
1537    /// thread-group leader's `ENOENT`, a permission refusal, an unwritable
1538    /// buffer), and Detcore what it names, the image's path. The bytes the
1539    /// kernel wrote past the shorter target are restored from `saved`, as
1540    /// Linux leaves them.
1541    async fn substitute_exe_link<G: Guest<Self>>(
1542        &self,
1543        guest: &mut G,
1544        (sysno, exe): (
1545            reverie::syscalls::Sysno,
1546            Option<Arc<crate::exec_record::ExecRecord>>,
1547        ),
1548        (buffer, buffer_len): (Option<AddrMut<'_, libc::c_char>>, usize),
1549        result: i64,
1550        saved: Option<&[u8]>,
1551    ) -> Result<i64, Error> {
1552        let (Some(buffer), Ok(kernel_len)) = (buffer, usize::try_from(result)) else {
1553            return Ok(result);
1554        };
1555        let present = exe.as_ref().filter(|exe| {
1556            self.guest_root(guest)
1557                .is_some_and(|root| exe.is_present(&root))
1558        });
1559        let Some(exe) = present else {
1560            restore_saved_link_bytes(guest, buffer, kernel_len, saved);
1561            return self.refuse_launched_exe(guest, sysno, exe.as_deref()).await;
1562        };
1563        let target = exe.exe.as_os_str().as_bytes();
1564        let written = target.len().min(readlink_size(buffer_len)?);
1565        guest
1566            .memory()
1567            .write_exact(buffer.cast::<u8>(), &target[..written])
1568            .map_err(|_| Errno::EFAULT)?;
1569        restore_link_tail(guest, buffer, written, kernel_len, saved)?;
1570        Ok(written as i64)
1571    }
1572
1573    /// The layout ([`crate::exec_record::ElfLayout`]) of the image the
1574    /// calling thread's exec ran, read from the exec record's file and checked
1575    /// to be the recorded inode, with that inode; or why there is none.
1576    fn recorded_image_layout<G: Guest<Self>>(
1577        &self,
1578        guest: &G,
1579    ) -> Result<(crate::exec_record::ElfLayout, u64), &'static str> {
1580        let exe = guest.thread_state().exe.clone().ok_or("no exec record")?;
1581        let root = self
1582            .guest_root(guest)
1583            .ok_or("the guest's root is unreadable")?;
1584        let path = root.join(
1585            exe.exe
1586                .strip_prefix("/")
1587                .map_err(|_| "a relative image path")?,
1588        );
1589        // Pin the object at the path without opening it for I/O (`O_PATH`, no
1590        // link followed), and read it only once it is the recorded regular
1591        // file: a FIFO or device put at the path since the exec is never
1592        // opened. Raw syscalls throughout: in-guest Detcore must not call
1593        // libc's wrappers (`crate::util::raw_syscall`).
1594        let pinned = crate::util::RawFd::open(&path, libc::O_PATH | libc::O_NOFOLLOW)
1595            .map_err(|_| "the image is unreadable")?;
1596        let stat = pinned.stat().map_err(|_| "the image is unreadable")?;
1597        if stat.st_mode & libc::S_IFMT != libc::S_IFREG
1598            || (stat.st_dev, stat.st_ino) != exe.identity()
1599        {
1600            return Err("the image's path names another file since the exec");
1601        }
1602        // Reopening the pinned descriptor's own procfs link opens the same
1603        // inode, whatever the path names by now.
1604        let file = crate::util::RawFd::open(
1605            Path::new(&format!("/proc/self/fd/{}", pinned.raw())),
1606            libc::O_RDONLY,
1607        )
1608        .map_err(|_| "the image is unreadable")?;
1609        let layout = crate::exec_record::ElfLayout::read_file(&file)
1610            .ok_or("the image is not an ELF64 executable")?;
1611        Ok((layout, stat.st_ino))
1612    }
1613
1614    /// Linux's start of the program break for the image the calling thread's
1615    /// exec ran: load_elf_binary's rule (`Self::recorded_image_layout`) at
1616    /// the load bias the process's `AT_PHDR` shows, or why there is none.
1617    fn modeled_start_brk<G: Guest<Self>>(&self, guest: &G) -> Result<u64, &'static str> {
1618        let (layout, _) = self.recorded_image_layout(guest)?;
1619        let auxv = self
1620            .guest_task_directory(guest)
1621            .and_then(|directory| crate::util::raw_read_file(&directory.join("auxv")).ok())
1622            .ok_or("the auxiliary vector is unreadable")?;
1623        let at_phdr = crate::exec_record::auxv_entry(&auxv, libc::AT_PHDR)
1624            .ok_or("the auxiliary vector has no AT_PHDR")?;
1625        layout.start_brk(at_phdr)
1626    }
1627
1628    /// Check Detcore's model of the program break for the image an exec just
1629    /// ran (`Self::modeled_start_brk`) against the kernel's `start_brk`
1630    /// (`/proc/<pid>/stat` field 47), and log the outcome
1631    /// ([`crate::exec_record::BrkCheck`]). A model that differs is a Detcore
1632    /// defect, reported as an error. The model is compared only where Linux's
1633    /// rule gives the kernel's start: not where the kernel randomized the
1634    /// break (`Self::break_randomized`), nor where that is unknown. The
1635    /// personality read is the process's current one. Every launcher Hermit
1636    /// execs a guest through sets `ADDR_NO_RANDOMIZE` before the exec, and a
1637    /// ptrace guest's own exec is checked at its exec stop, before any of the
1638    /// new image's code. The in-guest backends that declare no launcher
1639    /// (LiteInst, in-guest-trap) check only the image they launched: they
1640    /// refuse a guest's exec today. So a guest can only clear the flag before
1641    /// the check (a skipped comparison), not set it after a randomized exec.
1642    /// Should one of them come to follow an exec, its check would run after
1643    /// the new image's constructors, which could set the flag after a
1644    /// randomized exec; that case would need the exec-time personality. DBT
1645    /// and SaBRe, which follow execs, declare a launcher and take the branch
1646    /// below, which compares nothing with the kernel.
1647    ///
1648    /// Where the run declares a launcher, the kernel exec'd the launcher, so
1649    /// the process's auxiliary vector and break are the launcher's: Detcore
1650    /// keeps its own model instead (`Self::launched_brk_model`), with no
1651    /// kernel to compare it with, and answers `brk(2)` from it
1652    /// (`Self::handle_brk`). That needs Detcore's tool, which shares the
1653    /// guest's C library there, never to grow the guest's heap through the
1654    /// kernel's break; its `realpath` and `opendir` calls were removed for that
1655    /// (detcore/clippy.toml). Without a model, a brk is refused by name with
1656    /// the reason (`Detcore::handle_brk`).
1657    pub(crate) async fn check_brk_model<G: Guest<Self>>(&self, guest: &mut G) {
1658        use crate::exec_record::BrkCheck;
1659        let dettid = guest.thread_state().dettid;
1660        if self.declares_launcher() {
1661            let model = self.launched_brk_model(guest).await;
1662            match &model {
1663                Ok(model) => tracing::debug!(
1664                    "[detcore, dtid {}] program break serviced from a model starting at {:#x}: the run declares a launcher",
1665                    dettid,
1666                    model.start,
1667                ),
1668                Err(reason) => tracing::warn!(
1669                    "[detcore, dtid {}] program break not modeled: {}; a brk is refused by name",
1670                    dettid,
1671                    reason,
1672                ),
1673            }
1674            let mut metadata = guest
1675                .thread_state()
1676                .memory_metadata
1677                .lock()
1678                .expect("memory metadata mutex poisoned");
1679            metadata.brk_unmodeled = model.as_ref().err().map(|reason| (*reason).to_owned());
1680            metadata.brk_model = model.ok();
1681            return;
1682        }
1683        let check = {
1684            match self.modeled_start_brk(guest) {
1685                Err(reason) => BrkCheck::Unmodeled(reason),
1686                model => BrkCheck::of(
1687                    model,
1688                    self.break_randomized(guest),
1689                    self.kernel_start_brk(guest),
1690                ),
1691            }
1692        };
1693        if let BrkCheck::Differs { .. } = check {
1694            tracing::error!("[detcore, dtid {}] program break {}", dettid, check);
1695        } else {
1696            tracing::debug!("[detcore, dtid {}] program break {}", dettid, check);
1697        }
1698    }
1699
1700    /// Whether the run declares a launcher ([`crate::LaunchImage::launcher`]):
1701    /// the kernel exec'd it in the guest's place, so the process's auxiliary
1702    /// vector and program break are the launcher's.
1703    pub(crate) fn declares_launcher(&self) -> bool {
1704        self.cfg
1705            .launch_image
1706            .as_ref()
1707            .is_some_and(|image| image.launcher.is_some())
1708    }
1709
1710    /// Detcore's model of the program break for the image an exec just ran,
1711    /// where the run declares a launcher (`Self::declares_launcher`):
1712    /// load_elf_binary's rule (`Self::recorded_image_layout`) at the bias of
1713    /// the image's own executable mapping ([`crate::exec_record::load_bias`]),
1714    /// since the process's `AT_PHDR` is the launcher's. Or why there is none.
1715    async fn launched_brk_model<G: Guest<Self>>(
1716        &self,
1717        guest: &mut G,
1718    ) -> Result<crate::memory::BrkModel, &'static str> {
1719        // Detcore's brk transaction (`Self::handle_brk`) spans injected
1720        // calls, which Linux makes atomic under the address space's lock;
1721        // only sequentialized threads keep another thread out of it.
1722        if !self.cfg.sequentialize_threads {
1723            return Err("threads are not sequentialized");
1724        }
1725        let exe = guest.thread_state().exe.clone().ok_or("no exec record")?;
1726        let (layout, ino) = self.recorded_image_layout(guest)?;
1727        let maps = self
1728            .guest_task_directory(guest)
1729            .and_then(|directory| crate::util::raw_read_file(&directory.join("maps")).ok())
1730            .ok_or("the mappings are unreadable")?;
1731        let text = layout
1732            .text
1733            .ok_or("an image without an executable segment")?;
1734        let bias = crate::exec_record::load_bias(&maps, &exe.exe, ino, text)?;
1735        let start = layout.start_brk_at_bias(bias)?;
1736        // Guest code that ran before Detcore's first callback (a pre-init
1737        // function, an IFUNC resolver) used the kernel's break, the
1738        // launcher's, if it moved it: its heap is there, and a model elsewhere
1739        // would split it.
1740        let kernel_start = self
1741            .kernel_start_brk(guest)
1742            .ok_or("the kernel's start of the break is unreadable")?;
1743        let kernel_break = guest
1744            .inject_with_retry(reverie::syscalls::Syscall::Brk(
1745                reverie::syscalls::Brk::new().with_addr(None),
1746            ))
1747            .await
1748            .map_err(|_| "the kernel's break is unreadable")? as u64;
1749        if kernel_break != kernel_start {
1750            return Err("guest code moved the launcher's break before Detcore modeled its own");
1751        }
1752        tracing::debug!(
1753            target: "detcore::brk_diagnostic",
1754            dettid = guest.thread_state().dettid.as_raw(),
1755            image = ?exe.exe,
1756            identity = ?exe.identity(),
1757            image_inode = ino,
1758            layout = ?layout,
1759            bias,
1760            start,
1761            kernel_start,
1762            kernel_break,
1763            "BRK_MODEL_V1",
1764        );
1765        Ok(crate::memory::BrkModel {
1766            start,
1767            current: start,
1768            data_span: layout.data_span,
1769            launcher_break: kernel_start,
1770        })
1771    }
1772
1773    /// Whether the kernel randomized the calling thread's program break at
1774    /// its exec: it does where its process runs without `ADDR_NO_RANDOMIZE`
1775    /// (`/proc/<pid>/personality`) and `kernel.randomize_va_space` is above
1776    /// 1. `None` where either cannot be read.
1777    fn break_randomized<G: Guest<Self>>(&self, guest: &G) -> Option<bool> {
1778        let personality =
1779            crate::util::raw_read_file(&self.guest_task_directory(guest)?.join("personality"))
1780                .ok()?;
1781        let personality =
1782            u64::from_str_radix(std::str::from_utf8(&personality).ok()?.trim(), 16).ok()?;
1783        if personality & libc::ADDR_NO_RANDOMIZE as u64 != 0 {
1784            return Some(false);
1785        }
1786        let level =
1787            crate::util::raw_read_file(Path::new("/proc/sys/kernel/randomize_va_space")).ok()?;
1788        Some(
1789            std::str::from_utf8(&level)
1790                .ok()?
1791                .trim()
1792                .parse::<u32>()
1793                .ok()?
1794                > 1,
1795        )
1796    }
1797
1798    /// The kernel's `start_brk` for the calling thread's process, field 47 of
1799    /// its `/proc/<pid>/stat` ([`crate::exec_record::stat_start_brk`]), read
1800    /// where the tool reaches its procfs.
1801    fn kernel_start_brk<G: Guest<Self>>(&self, guest: &G) -> Option<u64> {
1802        let stat =
1803            crate::util::raw_read_file(&self.guest_task_directory(guest)?.join("stat")).ok()?;
1804        // The command name may be any bytes; the fields after it are ASCII.
1805        crate::exec_record::stat_start_brk(&String::from_utf8_lossy(&stat))
1806    }
1807
1808    /// Detcore's pid for the calling thread's process.
1809    pub(crate) fn own_detpid<G: Guest<Self>>(&self, guest: &G) -> crate::types::DetPid {
1810        guest.thread_state().detpid.unwrap_or(self.detpid)
1811    }
1812
1813    /// Project an already-completed own-ID query. Like `guest_visible_own_pid`,
1814    /// ordinary processes use the current thread's shared identity, including
1815    /// a fork child that kept the parent Tool. A nested namespace keeps the
1816    /// answer already delegated to the inner Tool, without a second injection.
1817    ///
1818    /// Detcore is a filter-map: a positive inner result establishes success,
1819    /// not the final guest identity. Preserve unusual nonpositive values;
1820    /// errors never reach this projection. This synchronous step adds no
1821    /// future around the existing syscall delegation.
1822    pub(crate) fn project_own_getter_result<G: Guest<Self>>(
1823        &self,
1824        guest: &G,
1825        call: Syscall,
1826        result: i64,
1827    ) -> i64 {
1828        if result <= 0 || guest.thread_state().nested_pid_namespace {
1829            return result;
1830        }
1831        match call {
1832            Syscall::Getpid(_) => i64::from(self.own_detpid(guest).as_raw()),
1833            Syscall::Gettid(_) => i64::from(guest.thread_state().dettid.as_raw()),
1834            _ => unreachable!("only own-ID getters have a shared result projection"),
1835        }
1836    }
1837
1838    /// Answer `readlink` of a `/proc` link whose target Detcore decides from
1839    /// its own model ([`decided_procfs_link`]), at the guest's absolute
1840    /// spelling `path` (for a guest pathname `spelled`), without asking the
1841    /// backend, so every backend answers alike (KVM's own `/proc` refuses
1842    /// `thread-self` and the namespace links). The caller's own descriptor
1843    /// link spelled through its thread is answered as `/proc/self/fd/N` is,
1844    /// with the kernel reading `/proc/thread-self/fd/N`, the calling thread's
1845    /// own table. Not in a nested PID namespace, where the caller's pid is
1846    /// not Detcore's, nor after a guest `chroot`, where `/proc` need not be
1847    /// procfs, nor for a pathname too long for Linux to look up.
1848    async fn readlink_decided_link<G: Guest<Self>>(
1849        &self,
1850        guest: &mut G,
1851        path: &Path,
1852        (spelled, link): (&Path, (i32, Option<PathPtr<'_>>)),
1853        buffer: Option<AddrMut<'_, libc::c_char>>,
1854        buffer_len: usize,
1855    ) -> Result<Option<i64>, Error> {
1856        let state = guest.thread_state();
1857        if state.nested_pid_namespace
1858            || state.changed_root.load(std::sync::atomic::Ordering::SeqCst)
1859            || spelled.as_os_str().len() >= libc::PATH_MAX as usize
1860        {
1861            return Ok(None);
1862        }
1863        let decided = decided_procfs_link(
1864            path.as_os_str().as_bytes(),
1865            self.own_detpid(guest).as_raw(),
1866            state.dettid.as_raw(),
1867        );
1868        let Some(decided) = decided else {
1869            return Ok(None);
1870        };
1871        // Linux takes the size as an int, and refuses one that is not
1872        // positive before it looks up the path.
1873        let size = readlink_size(buffer_len)?;
1874        if let DecidedLink::SelfFd(fd) = decided {
1875            return self
1876                .readlink_own_descriptor_link(guest, fd, link, buffer, size)
1877                .await
1878                .map(Some);
1879        }
1880        match decided {
1881            DecidedLink::Target(target) => {
1882                let copied = target.len().min(size);
1883                let address = buffer.ok_or(Errno::EFAULT)?;
1884                // Linux gives EFAULT for a buffer it cannot write; a backend's
1885                // write can fail otherwise (ptrace's EIO).
1886                guest
1887                    .memory()
1888                    .write_exact(address.cast::<u8>(), &target[..copied])
1889                    .map_err(|_| Errno::EFAULT)?;
1890                Ok(Some(copied as i64))
1891            }
1892            DecidedLink::Followed(errno) => Err(errno.into()),
1893            DecidedLink::SelfFd(_) => unreachable!("answered above"),
1894        }
1895    }
1896
1897    /// Answer `readlink` of the caller's own descriptor link `fd` spelled
1898    /// through its thread directory, into a buffer of `size` bytes, as
1899    /// `/proc/self/fd/N` is answered (a rendered procfs file's path, a
1900    /// placeholder's, or the kernel's link canonicalized), but by
1901    /// `/proc/thread-self/fd/N`, which every lookup here reads: a thread
1902    /// made without `CLONE_FILES`, or after `unshare(CLONE_FILES)`, has a
1903    /// table of its own, and the leader's may be gone. KVM's own `/proc`
1904    /// refuses `thread-self`, so there they read `/proc/self/fd/N`.
1905    async fn readlink_own_descriptor_link<G: Guest<Self>>(
1906        &self,
1907        guest: &mut G,
1908        fd: i32,
1909        link: (i32, Option<PathPtr<'_>>),
1910        buffer: Option<AddrMut<'_, libc::c_char>>,
1911        size: usize,
1912    ) -> Result<i64, Error> {
1913        let directory = if crate::procfs_inode::tool_can_name_guest_descriptors(&self.cfg.backend) {
1914            "thread-self"
1915        } else {
1916            "self"
1917        };
1918        let physical = PathBuf::from(format!("/proc/{directory}/fd/{fd}"));
1919        if let Some(result) = self
1920            .readlink_rendered_procfs(guest, &physical, buffer, size)
1921            .await?
1922        {
1923            return Ok(result);
1924        }
1925        let bytes = physical.as_os_str().as_bytes();
1926        let mut path_buffer = [0_u8; 64];
1927        path_buffer[..bytes.len()].copy_from_slice(bytes);
1928        let saved = saved_link_bytes(guest, buffer, size);
1929        let mut stack = guest.stack().await;
1930        let path_address = stack.push(path_buffer).cast::<libc::c_char>();
1931        let stack_guard = stack.commit()?;
1932        let call = syscalls::Readlink::new()
1933            .with_path(PathPtr::from_ptr(
1934                path_address.as_raw() as *const libc::c_char
1935            ))
1936            .with_buf(buffer)
1937            .with_bufsize(size);
1938        let result = self.record_or_replay(guest, call).await?;
1939        // The stack is released before anything else uses it; a placeholder
1940        // is confirmed through the guest's own pathname, as before.
1941        drop(stack_guard);
1942        self.finish_namespace_readlink_result(
1943            guest,
1944            link,
1945            physical,
1946            buffer,
1947            size,
1948            (result, saved.as_deref()),
1949        )
1950        .await
1951    }
1952
1953    // AUTONOMOUS-BOT-IMPLEMENTED
1954    // TODO-HUMAN-REVIEW(#877)
1955    /// Preserve Linux readlink errors and canonicalize procfs namespace identities.
1956    pub async fn handle_readlink<G: Guest<Self>>(
1957        &self,
1958        guest: &mut G,
1959        call: syscalls::Readlink,
1960    ) -> Result<i64, Error> {
1961        // Linux refuses a size that is not positive before it reads the path.
1962        readlink_size(call.bufsize())?;
1963        let path: PathBuf = call.path().ok_or(Errno::EFAULT)?.read(&guest.memory())?;
1964        if let Some(exe) = self
1965            .launched_exe(guest, (libc::AT_FDCWD, &path), false)
1966            .await
1967        {
1968            let saved = saved_exe_link_bytes(guest, call.buf(), call.bufsize());
1969            // As `readlinkat`, the same lookup: a launcher may answer an exact
1970            // `readlink` of the own link itself (SaBRe's plugin before
1971            // Reverie dropped it), and the kernel must decide existence.
1972            let kernel = syscalls::Readlinkat::new()
1973                .with_dirfd(libc::AT_FDCWD)
1974                .with_path(call.path())
1975                .with_buf(call.buf())
1976                .with_buf_len(call.bufsize());
1977            let result = self.record_or_replay(guest, kernel).await?;
1978            let buffer = (call.buf(), call.bufsize());
1979            return self
1980                .substitute_exe_link(
1981                    guest,
1982                    (reverie::syscalls::Sysno::readlink, exe),
1983                    buffer,
1984                    result,
1985                    saved.as_deref(),
1986                )
1987                .await;
1988        }
1989        let saved = self
1990            .declared_launcher()
1991            .and_then(|_| saved_exe_link_bytes(guest, call.buf(), call.bufsize()));
1992        let result = self.readlink_unlaunched(guest, call, path.clone()).await?;
1993        self.refuse_launcher_link(
1994            guest,
1995            (
1996                reverie::syscalls::Sysno::readlink,
1997                &path,
1998                (libc::AT_FDCWD, call.path()),
1999            ),
2000            (call.buf(), call.bufsize()),
2001            result,
2002            saved.as_deref(),
2003        )
2004        .await
2005    }
2006
2007    /// [`Self::handle_readlink`] of a link Detcore does not answer from an
2008    /// exec record.
2009    async fn readlink_unlaunched<G: Guest<Self>>(
2010        &self,
2011        guest: &mut G,
2012        call: syscalls::Readlink,
2013        path: PathBuf,
2014    ) -> Result<i64, Error> {
2015        if let Some(result) = self
2016            .readlink_rendered_procfs(guest, &path, call.buf(), call.bufsize())
2017            .await?
2018        {
2019            return Ok(result);
2020        }
2021        if let Some(result) = self
2022            .readlink_decided_link(
2023                guest,
2024                &path,
2025                (&path, (libc::AT_FDCWD, call.path())),
2026                call.buf(),
2027                call.bufsize(),
2028            )
2029            .await?
2030        {
2031            return Ok(result);
2032        }
2033        let (host_path, other_proc_fd) = if let Some((Some(subject), _)) = proc_fd_target(&path) {
2034            let current_pid = self.guest_visible_own_pid(guest).await?;
2035            (
2036                host_self_proc_fd_alias(&path, current_pid),
2037                current_pid != i64::from(subject),
2038            )
2039        } else {
2040            (None, false)
2041        };
2042        if let Some(host_path) = host_path {
2043            let bytes = host_path.as_os_str().as_bytes();
2044            let mut path_buffer = [0_u8; 64];
2045            path_buffer[..bytes.len()].copy_from_slice(bytes);
2046            let mut stack = guest.stack().await;
2047            let path_address = stack.push(path_buffer).cast::<libc::c_char>();
2048            let stack_guard = stack.commit()?;
2049            let physical_call = call.with_path(PathPtr::from_ptr(
2050                path_address.as_raw() as *const libc::c_char
2051            ));
2052            let result = self.record_or_replay(guest, physical_call).await?;
2053            drop(stack_guard);
2054            return self
2055                .canonicalize_namespace_readlink_result(
2056                    guest,
2057                    path,
2058                    call.buf(),
2059                    call.bufsize(),
2060                    result,
2061                )
2062                .await;
2063        }
2064        if other_proc_fd {
2065            return self.finish_other_proc_fd_readlink(guest, call).await;
2066        }
2067        self.finish_namespace_readlink(
2068            guest,
2069            (libc::AT_FDCWD, call.path()),
2070            path,
2071            call.buf(),
2072            call.bufsize(),
2073            call,
2074        )
2075        .await
2076    }
2077
2078    // AUTONOMOUS-BOT-IMPLEMENTED
2079    // TODO-HUMAN-REVIEW(#877)
2080    /// Preserve Linux readlinkat errors and canonicalize absolute procfs namespace identities.
2081    pub async fn handle_readlinkat<G: Guest<Self>>(
2082        &self,
2083        guest: &mut G,
2084        call: syscalls::Readlinkat,
2085    ) -> Result<i64, Error> {
2086        // Linux refuses a size that is not positive before it reads the path.
2087        readlink_size(call.buf_len())?;
2088        let path: PathBuf = call.path().ok_or(Errno::EFAULT)?.read(&guest.memory())?;
2089        if let Some(exe) = self.launched_exe(guest, (call.dirfd(), &path), false).await {
2090            let saved = saved_exe_link_bytes(guest, call.buf(), call.buf_len());
2091            let result = self.record_or_replay(guest, call).await?;
2092            let buffer = (call.buf(), call.buf_len());
2093            return self
2094                .substitute_exe_link(
2095                    guest,
2096                    (reverie::syscalls::Sysno::readlinkat, exe),
2097                    buffer,
2098                    result,
2099                    saved.as_deref(),
2100                )
2101                .await;
2102        }
2103        let saved = self
2104            .declared_launcher()
2105            .and_then(|_| saved_exe_link_bytes(guest, call.buf(), call.buf_len()));
2106        let result = self
2107            .readlinkat_unlaunched(guest, call, path.clone())
2108            .await?;
2109        self.refuse_launcher_link(
2110            guest,
2111            (
2112                reverie::syscalls::Sysno::readlinkat,
2113                &path,
2114                (call.dirfd(), call.path()),
2115            ),
2116            (call.buf(), call.buf_len()),
2117            result,
2118            saved.as_deref(),
2119        )
2120        .await
2121    }
2122
2123    /// [`Self::handle_readlinkat`] of a link Detcore does not answer from an
2124    /// exec record.
2125    async fn readlinkat_unlaunched<G: Guest<Self>>(
2126        &self,
2127        guest: &mut G,
2128        call: syscalls::Readlinkat,
2129        path: PathBuf,
2130    ) -> Result<i64, Error> {
2131        // A relative name below a directory descriptor is spelled as Linux
2132        // looks it up (`Detcore::procfs_spelling_at`): below a `/proc/self`
2133        // or `/proc/<pid>` directory, the task the directory was opened on
2134        // (ESRCH once that task is gone), and below a descriptor Detcore has
2135        // no record of (one received over `SCM_RIGHTS`), the procfs directory
2136        // the kernel names for it; so a namespace or descriptor link there is
2137        // modeled and canonicalized as the same link spelled absolutely. Any
2138        // other such name stays relative, and the kernel decides.
2139        let below_directory =
2140            !path.is_absolute() && !path.as_os_str().is_empty() && call.dirfd() != libc::AT_FDCWD;
2141        let recorded = if path.is_absolute() || call.dirfd() == libc::AT_FDCWD {
2142            None
2143        } else {
2144            guest
2145                .thread_state()
2146                .with_detfd(call.dirfd(), |detfd| detfd.path())
2147                .unwrap_or(None)
2148        };
2149        let lexical = if path.is_absolute() || call.dirfd() == libc::AT_FDCWD {
2150            path.clone()
2151        } else {
2152            recorded
2153                .as_ref()
2154                .map_or(path.clone(), |directory| directory.join(&path))
2155        };
2156        let observed_path = if below_directory {
2157            self.procfs_spelling_at(guest, call.dirfd(), &path).await?
2158        } else {
2159            lexical.clone()
2160        };
2161        // The directory names a task or a kernel path Detcore knows.
2162        let named_by_directory = below_directory && observed_path != lexical;
2163        if let Some(result) = self
2164            .readlink_rendered_procfs(guest, &observed_path, call.buf(), call.buf_len())
2165            .await?
2166        {
2167            return Ok(result);
2168        }
2169        // A relative pathname is decided only below a descriptor on `/proc`
2170        // itself, a directory, or one whose task or kernel path Detcore knows
2171        // (a selector's directory records its task only where the open
2172        // followed the selector, not for the link itself, an
2173        // `O_PATH | O_NOFOLLOW` open of `/proc/self`). An empty pathname reads
2174        // the descriptor's own link, which the kernel answers (an inherited
2175        // one keeps its opener's binding).
2176        let decidable = path.is_absolute()
2177            || named_by_directory
2178            || (below_directory
2179                && recorded
2180                    .as_deref()
2181                    .is_some_and(|directory| directory == Path::new("/proc")));
2182        if decidable
2183            && let Some(result) = self
2184                .readlink_decided_link(
2185                    guest,
2186                    &observed_path,
2187                    (&path, (call.dirfd(), call.path())),
2188                    call.buf(),
2189                    call.buf_len(),
2190                )
2191                .await?
2192        {
2193            return Ok(result);
2194        }
2195        if let Some((Some(subject), _)) = proc_fd_target(&observed_path) {
2196            let current_pid = self.guest_visible_own_pid(guest).await?;
2197            if current_pid != i64::from(subject) {
2198                return self.finish_other_proc_fd_readlinkat(guest, call).await;
2199            }
2200        }
2201        self.finish_namespace_readlink(
2202            guest,
2203            (call.dirfd(), call.path()),
2204            observed_path,
2205            call.buf(),
2206            call.buf_len(),
2207            call,
2208        )
2209        .await
2210    }
2211}
2212
2213#[cfg(test)]
2214mod tests {
2215    /// A failed probe (here, the pipe's descriptor limit) is kept as its kind
2216    /// and errno number, not the C library's message, which `to_string`
2217    /// fetches through strerror_r.
2218    #[test]
2219    fn a_failed_device_probe_is_kept_without_the_c_library_message() {
2220        let failure = || std::io::Error::from_raw_os_error(libc::EMFILE);
2221        assert!(failure().to_string().contains("Too many open files"));
2222        let kept = super::retained_probe_outcome(Err(failure())).unwrap_err();
2223        assert!(kept.ends_with("(errno 24)"), "{kept}");
2224        assert!(!kept.contains("Too many open files"), "{kept}");
2225    }
2226
2227    use super::*;
2228
2229    /// The devices read once are the pipe and socket filesystems' own: a
2230    /// fresh pipe and socket show the same ones, and the two differ.
2231    #[test]
2232    fn anonymous_object_devices_are_the_pipe_and_socket_filesystems() {
2233        let read = anonymous_object_devices();
2234        let devices = read.as_ref().unwrap();
2235        assert_eq!(&probe_anonymous_object_devices().unwrap(), devices);
2236        assert_ne!(devices.pipe, devices.socket);
2237        assert_eq!(anonymous_object_device(read, "pipe").unwrap(), devices.pipe);
2238        assert_eq!(
2239            anonymous_object_device(read, "socket").unwrap(),
2240            devices.socket
2241        );
2242        // Devices that could not be read at start, as with the process's
2243        // descriptors exhausted, fail the run as a tool error and never
2244        // reach the guest as an errno.
2245        let unread = Err("Too many open files (os error 24)".to_string());
2246        for kind in ["pipe", "socket"] {
2247            let error = anonymous_object_device(&unread, kind).unwrap_err();
2248            assert!(matches!(error, Error::Tool(_)), "{error:?}");
2249            assert!(error.to_string().contains("os error 24"), "{error}");
2250        }
2251    }
2252
2253    #[test]
2254    fn names_whose_exe_link_a_spelling_reads() {
2255        let subject = |path: &str| exe_link_subject(path.as_bytes(), 3);
2256        for path in [
2257            "/proc/self/exe",
2258            "/proc/thread-self/exe",
2259            "/proc/3/exe",
2260            "/proc//self/./exe",
2261            "/proc/self/task/5/exe",
2262            "/proc/3/task/7/exe",
2263        ] {
2264            assert_eq!(subject(path), Some(ExeLinkSubject::Own), "{path}");
2265        }
2266        assert_eq!(subject("/proc/4/exe"), Some(ExeLinkSubject::Other(4)));
2267        assert_eq!(
2268            subject("/proc/4/task/9/exe"),
2269            Some(ExeLinkSubject::Other(4))
2270        );
2271        for path in [
2272            "/proc/self/exe/",
2273            "/proc/self/exe/.",
2274            "/proc/self/../self/exe",
2275            "/proc/04/exe",
2276            "/proc/self/cwd",
2277            "/proc/thread-self/task/5/exe",
2278            "/proc/self/task/x/exe",
2279            "/proc/exe",
2280            "proc/self/exe",
2281            "/tmp/self/exe",
2282        ] {
2283            assert_eq!(subject(path), None, "{path}");
2284        }
2285    }
2286
2287    #[test]
2288    fn decides_the_links_detcore_knows_the_targets_of() {
2289        let decided = |path: &str| decided_procfs_link(path.as_bytes(), 3, 5);
2290        let target = |bytes: &[u8]| Some(DecidedLink::Target(bytes.to_vec()));
2291        assert_eq!(decided("/proc/self"), target(b"3"));
2292        assert_eq!(decided("/proc/./self"), target(b"3"));
2293        assert_eq!(decided("/proc/thread-self"), target(b"3/task/5"));
2294        assert_eq!(decided("/proc/mounts"), target(b"self/mounts"));
2295        assert_eq!(decided("/proc/net"), target(b"self/net"));
2296        assert_eq!(decided("/proc/self/ns/pid"), target(b"pid:[4026531836]"));
2297        assert_eq!(decided("/proc/3/ns/mnt"), target(b"mnt:[4026531841]"));
2298        assert_eq!(
2299            decided("/proc/thread-self/ns/user"),
2300            target(b"user:[4026531837]")
2301        );
2302        assert_eq!(
2303            decided("/proc/3/task/5/ns/net"),
2304            decided("/proc/self/ns/net")
2305        );
2306        assert_eq!(
2307            decided("/proc/self/task/5/fd/7"),
2308            Some(DecidedLink::SelfFd(7))
2309        );
2310        assert_eq!(decided("/proc/3/task/5/fd/0"), Some(DecidedLink::SelfFd(0)));
2311        assert_eq!(decided("/proc//self"), target(b"3"));
2312        // Linux takes the size as an int.
2313        assert_eq!(readlink_size(0), Err(Errno::EINVAL));
2314        assert_eq!(readlink_size(1 << 31), Err(Errno::EINVAL));
2315        assert_eq!(readlink_size((1 << 32) + 5), Ok(5));
2316        assert_eq!(readlink_size(i32::MAX as usize), Ok(i32::MAX as usize));
2317        assert_eq!(decided("/proc/self/ns/./pid"), decided("/proc/self/ns/pid"));
2318        // A trailing slash or `.` follows the link: to a directory, EINVAL; to
2319        // a file, ENOTDIR.
2320        let followed = |errno| Some(DecidedLink::Followed(errno));
2321        for path in [
2322            "/proc/self/",
2323            "/proc/self/.",
2324            "/proc/self//",
2325            "/proc/thread-self/",
2326            "/proc/net/",
2327        ] {
2328            assert_eq!(decided(path), followed(Errno::EINVAL), "{path}");
2329        }
2330        for path in [
2331            "/proc/mounts/",
2332            "/proc/mounts/.",
2333            "/proc/self/ns/pid/",
2334            "/proc/thread-self/ns/pid/.",
2335            "/proc/3/task/5/ns/net/",
2336        ] {
2337            assert_eq!(decided(path), followed(Errno::ENOTDIR), "{path}");
2338        }
2339        // Left to the kernel: `..`, a followed descriptor link, another
2340        // process's or thread's links, unknown namespaces, and links Detcore
2341        // does not decide yet.
2342        for path in [
2343            "/proc/self/task/5/fd/7/",
2344            "/proc/4/",
2345            "/proc/",
2346            "/proc/self/../self",
2347            "/proc/4/ns/pid",
2348            "/proc/self/task/6/ns/pid",
2349            "/proc/self/task/6/fd/7",
2350            "/proc/self/ns/unknown",
2351            "/proc/self/fd/7",
2352            "/proc/self/exe",
2353            "/proc/self/cwd",
2354            "/proc/selfx",
2355            "/tmp/self",
2356            "proc/self",
2357        ] {
2358            assert_eq!(decided(path), None, "{path}");
2359        }
2360    }
2361
2362    #[test]
2363    fn recognizes_process_and_thread_namespace_links() {
2364        assert_eq!(
2365            canonical_namespace_target(Path::new("/proc/self/ns/mnt")),
2366            Some(b"mnt:[4026531841]".as_slice())
2367        );
2368        assert_eq!(
2369            canonical_namespace_target(Path::new("/proc/123/task/456/ns/user")),
2370            Some(b"user:[4026531837]".as_slice())
2371        );
2372        assert_eq!(
2373            canonical_namespace_target(Path::new("/proc/thread-self/ns/pid_for_children")),
2374            Some(b"pid:[4026531836]".as_slice())
2375        );
2376    }
2377
2378    #[test]
2379    fn leaves_non_namespace_and_relative_links_untouched() {
2380        assert_eq!(
2381            canonical_namespace_target(Path::new("/proc/self/exe")),
2382            None
2383        );
2384        assert_eq!(canonical_namespace_target(Path::new("/tmp/ns/mnt")), None);
2385        assert_eq!(
2386            canonical_namespace_target(Path::new("proc/self/ns/mnt")),
2387            None
2388        );
2389        assert_eq!(
2390            canonical_namespace_target(Path::new("/proc/self/ns/unknown")),
2391            None
2392        );
2393    }
2394
2395    #[test]
2396    fn recognizes_proc_fd_aliases_and_lexical_normalization() {
2397        for (path, expected) in [
2398            ("/proc/self/fd/1", (None, 1)),
2399            ("/proc/thread-self/fd/20", (None, 20)),
2400            ("/proc/123/fd/7", (Some(123), 7)),
2401            ("/proc/self/fd/../fd/9", (None, 9)),
2402            ("/dev/fd/3", (None, 3)),
2403        ] {
2404            assert_eq!(proc_fd_target(Path::new(path)), Some(expected), "{path}");
2405        }
2406    }
2407
2408    #[test]
2409    fn rewrites_only_numeric_virtual_self_proc_fd_aliases() {
2410        assert_eq!(
2411            host_self_proc_fd_alias(Path::new("/proc/123/fd/7"), 123),
2412            Some(PathBuf::from("/proc/self/fd/7"))
2413        );
2414        assert_eq!(
2415            host_self_proc_fd_alias(Path::new("/proc/124/fd/7"), 123),
2416            None
2417        );
2418        assert_eq!(
2419            host_self_proc_fd_alias(Path::new("/proc/self/fd/7"), 123),
2420            None
2421        );
2422    }
2423
2424    /// The caller's own descriptor links, by every spelling procfs and
2425    /// `/dev/fd` give them, name its descriptor, in the process's table or
2426    /// the thread's; another process's or thread's, a spelling through `..`,
2427    /// a relative one, or a name below the link do not.
2428    #[test]
2429    fn own_descriptor_links_name_the_callers_descriptor() {
2430        use DescriptorTable::Process;
2431        use DescriptorTable::Thread;
2432        let own = Some((3, 5));
2433        for (path, fd, table) in [
2434            ("/dev/fd/7", 7, Process),
2435            ("/proc/self/fd/7", 7, Process),
2436            ("/proc/thread-self/fd/7", 7, Thread),
2437            ("/proc/3/fd/0", 0, Process),
2438            ("/proc/3/task/5/fd/12", 12, Thread),
2439            ("/proc/self/task/5/fd/12", 12, Thread),
2440            ("/proc/self/fd/7/", 7, Process),
2441            ("/proc/./self/fd/7", 7, Process),
2442            ("//dev//fd//7", 7, Process),
2443            ("/proc/thread-self/fd/7/.", 7, Thread),
2444        ] {
2445            assert_eq!(
2446                own_descriptor_link(Path::new(path), own),
2447                Some(DescriptorLink { fd, table }),
2448                "{path}"
2449            );
2450        }
2451        for path in [
2452            "/proc/4/fd/7",
2453            "/proc/3/task/6/fd/7",
2454            "/proc/thread-self/task/5/fd/7",
2455            "/proc/self/fd/07",
2456            "/proc/self/fd/7/stat",
2457            "/proc/self/fd",
2458            "/proc/self/../self/fd/7",
2459            "/dev/fd/../fd/7",
2460            "proc/self/fd/7",
2461            "/proc/self/fdinfo/7",
2462            "/dev/fd/x",
2463        ] {
2464            assert_eq!(own_descriptor_link(Path::new(path), own), None, "{path}");
2465        }
2466        // Without the caller's procfs names, only the spellings without
2467        // numbers are its own.
2468        let fd = |fd, table| Some(DescriptorLink { fd, table });
2469        assert_eq!(
2470            own_descriptor_link(Path::new("/proc/self/fd/7"), None),
2471            fd(7, Process)
2472        );
2473        assert_eq!(
2474            own_descriptor_link(Path::new("/proc/thread-self/fd/7"), None),
2475            fd(7, Thread)
2476        );
2477        assert_eq!(
2478            own_descriptor_link(Path::new("/dev/fd/7"), None),
2479            fd(7, Process)
2480        );
2481        assert_eq!(own_descriptor_link(Path::new("/proc/3/fd/7"), None), None);
2482        assert_eq!(
2483            own_descriptor_link(Path::new("/proc/self/task/5/fd/7"), None),
2484            None
2485        );
2486    }
2487
2488    /// The paths procfs and `/dev` resolve for whoever looks them up, and
2489    /// the ones they do not.
2490    #[test]
2491    fn caller_selectors_are_the_ones_procfs_resolves_per_caller() {
2492        for path in [
2493            "/proc/self",
2494            "/proc/self/",
2495            "/proc/self/task",
2496            "/proc/thread-self",
2497            "/proc/thread-self/fd",
2498            "/proc/mounts",
2499            "/proc/net",
2500            "/proc/net/tcp",
2501            "/dev/fd",
2502            "/dev/fd/3",
2503            "/dev/stdin",
2504            "/dev/stdout",
2505            "/dev/stderr",
2506            "//proc/./self",
2507            "/proc/sys/../self",
2508            "/tmp/../proc/stat",
2509            "relative/dir",
2510        ] {
2511            assert!(names_through_caller_selector(Path::new(path)), "{path}");
2512        }
2513        for path in [
2514            "/",
2515            "/proc",
2516            "/proc/",
2517            "/proc/1",
2518            "/proc/12/task/13",
2519            "/proc/stat",
2520            "/proc/sys/kernel",
2521            "/proc/selfish",
2522            "/dev",
2523            "/dev/null",
2524            "/tmp/self",
2525        ] {
2526            assert!(!names_through_caller_selector(Path::new(path)), "{path}");
2527        }
2528    }
2529
2530    #[test]
2531    fn rejects_non_proc_fd_targets() {
2532        for path in [
2533            "/proc/self/fd/",
2534            "/proc/self/fd/stdout",
2535            "/proc/self/fd/1/status",
2536            "/proc/not-a-pid/fd/1",
2537            "/dev/fd/-1",
2538            "proc/self/fd/1",
2539        ] {
2540            assert_eq!(proc_fd_target(Path::new(path)), None, "{path}");
2541        }
2542    }
2543
2544    #[test]
2545    fn recognizes_only_anonymous_pipe_and_socket_targets() {
2546        assert_eq!(
2547            anonymous_proc_fd_identity(b"pipe:[987654321]"),
2548            Some(AnonymousProcFdIdentity {
2549                kind: "pipe",
2550                raw_inode: 987_654_321,
2551            })
2552        );
2553        assert_eq!(
2554            anonymous_proc_fd_identity(b"socket:[42]"),
2555            Some(AnonymousProcFdIdentity {
2556                kind: "socket",
2557                raw_inode: 42,
2558            })
2559        );
2560
2561        for target in [
2562            b"pip".as_slice(),
2563            b"socket:[12345".as_slice(),
2564            b"/tmp/regular-file".as_slice(),
2565            b"anon_inode:[eventpoll]".as_slice(),
2566            b"pipe:[]".as_slice(),
2567            b"pipe:[12]suffix".as_slice(),
2568            b"socket:[not-a-number]".as_slice(),
2569        ] {
2570            assert_eq!(anonymous_proc_fd_identity(target), None, "{target:?}");
2571        }
2572    }
2573
2574    #[test]
2575    fn short_buffers_use_scratch_large_enough_for_every_anonymous_target() {
2576        assert!(!needs_anonymous_proc_fd_scratch(false, 1));
2577        assert!(!needs_anonymous_proc_fd_scratch(true, 0));
2578        assert!(needs_anonymous_proc_fd_scratch(true, 1));
2579        assert!(needs_anonymous_proc_fd_scratch(
2580            true,
2581            ANONYMOUS_PROC_FD_TARGET_CAPACITY - 1
2582        ));
2583        assert!(!needs_anonymous_proc_fd_scratch(
2584            true,
2585            ANONYMOUS_PROC_FD_TARGET_CAPACITY
2586        ));
2587
2588        let maximum = format!("socket:[{}]", u64::MAX);
2589        assert!(maximum.len() < ANONYMOUS_PROC_FD_TARGET_CAPACITY);
2590        // The longest link a placeholder can have: the longest memfd name
2591        // (249 bytes) in `/memfd:<name> (deleted)`.
2592        let longest = format!("/memfd:{} (deleted)", "x".repeat(249));
2593        assert!(longest.len() < ANONYMOUS_PROC_FD_TARGET_CAPACITY);
2594        // Each rendered file's placeholder, with the snapshot it carries,
2595        // fits a memfd name and is read back from its link in a session that
2596        // renders it. A file whose snapshots are all the same carries none
2597        // (`ProcfsFile::snapshot_is_rerendered`).
2598        let all = crate::procfs::RenderedFiles::ALL;
2599        for path in crate::syscalls::rendered_procfs::rendered_paths(all) {
2600            let path = std::path::Path::new(path.to_str().unwrap());
2601            let rerendered = crate::procfs::ProcfsFile::from_path(path)
2602                .unwrap()
2603                .snapshot_is_rerendered();
2604            let snapshot = match rerendered {
2605                true => Vec::new(),
2606                false => b"00000000-0000-4000-8000-000000000000\n".to_vec(),
2607            };
2608            let name = crate::procfs::placeholder_name(path, &snapshot);
2609            assert!(name.len() <= 249, "{name}");
2610            let placeholder = format!("/memfd:{name} (deleted)");
2611            assert!(crate::procfs::placeholder_link_path(placeholder.as_bytes(), all).is_some());
2612        }
2613        assert_eq!(
2614            anonymous_proc_fd_identity(maximum.as_bytes()),
2615            Some(AnonymousProcFdIdentity {
2616                kind: "socket",
2617                raw_inode: u64::MAX,
2618            })
2619        );
2620    }
2621
2622    #[test]
2623    fn stdio_identity_requires_a_raw_inode_match_and_preserves_alias_precedence() {
2624        let raw = |ino| RawInode::new(9, ino);
2625        let stdio = [Some(raw(11)), Some(raw(22)), Some(raw(33))];
2626        assert_eq!(
2627            deterministic_stdio_inode_for_raw(raw(22), &stdio),
2628            Some(DetInode::mint(1001))
2629        );
2630        assert_eq!(deterministic_stdio_inode_for_raw(raw(44), &stdio), None);
2631        // The same number on another device is another file.
2632        assert_eq!(
2633            deterministic_stdio_inode_for_raw(RawInode::new(10, 22), &stdio),
2634            None
2635        );
2636
2637        let aliased = [None, Some(raw(55)), Some(raw(55))];
2638        assert_eq!(
2639            deterministic_stdio_inode_for_raw(raw(55), &aliased),
2640            Some(DetInode::mint(1001))
2641        );
2642        // What `setup_stdio` caches: stdin's identity on all three.
2643        let inherited = [Some(raw(66)); 3];
2644        assert_eq!(
2645            deterministic_stdio_inode_for_raw(raw(66), &inherited),
2646            Some(DetInode::mint(1000))
2647        );
2648    }
2649
2650    #[test]
2651    fn anonymous_target_rewrite_ignores_raw_inode_width_and_truncates_to_buffer() {
2652        let short_raw = anonymous_proc_fd_identity(b"pipe:[42]").unwrap();
2653        let long_raw = anonymous_proc_fd_identity(b"pipe:[987654321]").unwrap();
2654        let short_rewrite =
2655            canonical_anonymous_proc_fd_target(&short_raw, DetInode::mint(1001), usize::MAX);
2656        let long_rewrite =
2657            canonical_anonymous_proc_fd_target(&long_raw, DetInode::mint(1001), usize::MAX);
2658        assert_eq!(short_rewrite, b"pipe:[1001]");
2659        assert_eq!(long_rewrite, short_rewrite);
2660
2661        assert_eq!(
2662            canonical_anonymous_proc_fd_target(&long_raw, DetInode::mint(1001), 8),
2663            b"pipe:[10"
2664        );
2665    }
2666}