Skip to main content

detcore/syscalls/
signal.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//! System calls dealing with signals.
10
11use std::time::Duration;
12
13use detcore_model::bundled_signal_facts;
14use detcore_model::schedule::SigWrapper;
15use nix::sys::signal::Signal;
16use reverie::Errno;
17use reverie::Error;
18use reverie::Guest;
19use reverie::Stack;
20use reverie::syscalls;
21use reverie::syscalls::Addr;
22use reverie::syscalls::AddrMut;
23use reverie::syscalls::MemoryAccess;
24use reverie::syscalls::Sysno;
25use reverie::syscalls::Timespec;
26use tracing::info;
27
28use crate::Detcore;
29use crate::fd::FdType;
30use crate::record_or_replay::RecordOrReplay;
31use crate::resources::InGuestSleepSigalrm;
32use crate::resources::Permission;
33use crate::resources::ResourceID;
34use crate::resources::Resources;
35use crate::resources::SigalrmSleepDisposition;
36use crate::scheduler::HostTimedSignalScope;
37use crate::scheduler::OwnProcessSignalInputs;
38use crate::scheduler::SiblingSignalState;
39use crate::scheduler::discarded_at_send::DiscardToken;
40use crate::scheduler::discarded_at_send::DiscardedSignalAnswer;
41use crate::scheduler::discarded_at_send::DiscardedSignalControl;
42use crate::scheduler::discarded_at_send::QueueId;
43use crate::scheduler::pid_namespaces::GuestPidAnswer;
44use crate::scheduler::signal_lists::KernelSiginfo;
45use crate::syscalls::helpers::REAL_TIME_SIGNALS;
46use crate::syscalls::helpers::act_on_pending_real_time;
47use crate::syscalls::helpers::observe_under_mask;
48use crate::syscalls::helpers::pending_real_time_among;
49use crate::syscalls::helpers::retry_nonblocking_syscall_with_timeout;
50use crate::syscalls::helpers::unblocked_by;
51use crate::syscalls::threads::KERNEL_SIGSET_SIZE;
52use crate::syscalls::threads::KernelSigaction;
53use crate::syscalls::threads::KernelSigset;
54use crate::syscalls::threads::kernel_sigset_bit;
55use crate::syscalls::threads::read_thread_wait_signal_state;
56use crate::tool_global::ResumeStatus;
57use crate::tool_global::SigalrmControl;
58use crate::tool_global::alarm_remaining;
59use crate::tool_global::commit_sigkill;
60use crate::tool_global::host_timed_signals;
61use crate::tool_global::names_a_retired_exited_leader;
62use crate::tool_global::notify_signal_pending;
63use crate::tool_global::own_process_signal_inputs;
64use crate::tool_global::record_host_timed_signals;
65use crate::tool_global::refuse_sigalrm;
66use crate::tool_global::register_alarm;
67use crate::tool_global::registered_process_of;
68use crate::tool_global::reserve_sigkill;
69use crate::tool_global::reserve_sigkill_group;
70use crate::tool_global::resolve_kill_targets_and_exit;
71use crate::tool_global::resource_request;
72use crate::tool_global::set_sigchld_disposition;
73use crate::tool_global::set_sigtimedwait_set;
74use crate::tool_global::sigalrm_refuses;
75use crate::tool_global::signal_target_process;
76use crate::tool_global::thread_observe_time;
77use crate::types::DetPid;
78use crate::types::DetTid;
79use crate::types::LogicalTime;
80
81/// Signals hermit takes from the guest's namespace, and what a guest loses.
82///
83/// ⚠️ ENUMERATED BY MEASUREMENT, NOT BY READING (2026-08-25). Every signal 1..64
84/// was run under two delivery paths -- self-directed `raise` and a sibling
85/// thread's `pthread_kill` -- with a native run as the control for each. Exactly
86/// TWO differ from native, and they fail in different ways at different points:
87///
88///   SIGSTKFLT (16)  `rt_sigaction` is NO-OPED below, so the handler is never
89///                   installed and the default disposition terminates the guest:
90///                   observed exit 144 (= 128 + 16).
91///   SIGTRAP    (5)  `rt_sigaction` passes through and the handler IS installed,
92///                   but ptrace consumes every SIGTRAP (syscall stops, seccomp
93///                   stops, breakpoints), so the handler never runs. ⚠️ THE GUEST
94///                   THEN EXITS 0 WITH NO DIAGNOSTIC AT ALL -- a clean pass that
95///                   behaved differently from native, which no cell can catch.
96///
97/// Everything else in 1..31 matches native exactly; 9/19 and 32/33 refuse
98/// `sigaction` natively too and are not hermit's. Realtime 34..64 are
99/// delivered and handled like any other signal under ptrace
100/// (<https://github.com/rrnewton/reverie/issues/207>); they are not
101/// appropriation.
102const APPROPRIATED_SIGNALS: [(i32, &str); 2] = [
103    (
104        libc::SIGTRAP,
105        "ptrace consumes every SIGTRAP (syscall/seccomp stops, breakpoints)",
106    ),
107    (
108        libc::SIGSTKFLT,
109        "reverie uses it as PERF_EVENT_SIGNAL, the PMU preemption timer",
110    ),
111];
112
113/// Say, once per installation, that a guest handler will never run.
114///
115/// ⚠️ WHY A DIAGNOSTIC AND NOT A REFUSAL. Returning `EINVAL` from `sigaction`
116/// was considered and deliberately rejected for SIGSTKFLT -- see the comment at
117/// the no-op below: the Go runtime registers that handler, and refusing would
118/// break every Go guest at startup. That reasoning generalises: installing a
119/// handler defensively is common, actually raising these signals is rare, so
120/// refusal breaks MORE programs than the current behaviour. The contract
121/// question of what a guest is owed here is genuinely open.
122///
123/// What is NOT open is that hermit currently says NOTHING. This line commits to
124/// no policy, breaks no conforming program, and turns a silent wrong answer into
125/// a visible one -- the same reasoning as the `HERMIT_INTERNAL_FAILURE` marker.
126/// The decision, separated from the reporting so a test can exercise THIS and
127/// not a copy of it. A unit test that re-implements a predicate keeps passing
128/// when the real one is gutted -- measured in this project's own pipe work,
129/// where deleting the production wiring left every unit test green.
130fn appropriated_reason(signum: i32, handler: u64) -> Option<&'static str> {
131    // SIG_DFL (0) and SIG_IGN (1) lose nothing: the guest is not asking to be
132    // called back, so there is no expectation to disappoint.
133    if handler <= 1 {
134        return None;
135    }
136    APPROPRIATED_SIGNALS
137        .iter()
138        .find(|(s, _)| *s == signum)
139        .map(|(_, why)| *why)
140}
141
142fn warn_appropriated_signal(signum: i32, handler: u64) {
143    if let Some(why) = appropriated_reason(signum, handler) {
144        tracing::warn!(
145            "HERMIT_APPROPRIATED_SIGNAL signum={signum} effect=handler-installed-but-never-invoked reason={why}"
146        );
147    }
148}
149
150// NB: the kernel uses an eight-byte signal mask in its raw signal syscalls on
151// x86_64. `libc::sigset_t` is the 128-byte userspace wrapper type and must not
152// be used to access these buffers. See:
153// https://elixir.bootlin.com/linux/latest/source/include/uapi/asm-generic/signal.h#L75
154fn validate_kernel_sigset_size(sigsetsize: usize) -> Result<(), Errno> {
155    if sigsetsize == KERNEL_SIGSET_SIZE {
156        Ok(())
157    } else {
158        Err(Errno::EINVAL)
159    }
160}
161
162/// The mask Linux installs when a call names `mask` as the signal mask to sleep
163/// under (`rt_sigsuspend`, `ppoll`, `pselect6`): `set_current_blocked` drops
164/// `SIGKILL` and `SIGSTOP`, which can never be blocked.
165pub(crate) fn kernel_installed_signal_mask(mask: KernelSigset) -> KernelSigset {
166    let unblockable = (1_u64 << (libc::SIGKILL - 1)) | (1_u64 << (libc::SIGSTOP - 1));
167    mask & !unblockable
168}
169
170fn without_perf_event_signal(mask: KernelSigset) -> KernelSigset {
171    let bit = (reverie::PERF_EVENT_SIGNAL as u32) - 1;
172    mask & !(1_u64 << bit)
173}
174
175/// The result of a kernel-access probe that is a call's first injection,
176/// made before anything of the call happens (`read_kernel_sigset`,
177/// `read_kernel_sigaction`, pselect6's wrapper validation), with the
178/// backend's not-run report, `-ERESTARTSYS` (which no probe returns
179/// itself), turned into `-ERESTARTNOINTR`. The report means a signal reached
180/// the thread at the call's entry and stopped the probe before its `syscall`
181/// instruction; the backend holds it. The call then restarts once the signal
182/// is delivered, as if the signal had come before the call: its handler runs
183/// under the thread's own mask, and the call runs. Ending the call with the
184/// not-run report instead returned EINTR, from a wait whose temporary mask
185/// the handler never saw and from calls that never fail with EINTR
186/// (`rt_sigprocmask`, `rt_sigaction`), which no Linux run produces
187/// (https://github.com/rrnewton/hermit/issues/4526).
188///
189/// Only for a call's first injection. A probe after an earlier injection
190/// keeps the not-run report, since a restart would repeat that injection
191/// (pselect6's mask read after its wrapper validation and its observation of
192/// a pending real-time timer expiration, for example). Some first injections
193/// still keep it, because whether they come first depends on an earlier
194/// phase that usually injects nothing
195/// (https://github.com/rrnewton/hermit/issues/4526):
196/// - raw epoll_pwait and epoll_pwait2: the mask read inside
197///   `observe_under_temporary_mask`, which swallows any error, and the mask
198///   reads after it when the observation injected nothing;
199/// - a zero-timeout ppoll's mask read (`prepare_ppoll_probe(.., false)`):
200///   in run mode it follows `publish_expired`, which usually injects
201///   nothing; under record and replay only a scheduler request comes first,
202///   so there it is always the first injection, and still unmapped;
203/// - record/replay pselect6's entry read (`entry_pselect6_temporary_mask`),
204///   which swallows any error.
205pub(crate) fn restart_if_first_probe_not_run<V>(result: Result<V, Error>) -> Result<V, Error> {
206    match result {
207        Err(Error::Errno(Errno::ERESTARTSYS)) => Err(Errno::ERESTARTNOINTR.into()),
208        other => other,
209    }
210}
211
212/// Read one raw kernel signal mask while preserving the kernel's user-access check.
213///
214/// `safeptrace::Stopped::read` deliberately uses `PTRACE_PEEKDATA` for reads of
215/// eight bytes or less. That operation can read a `PROT_NONE` page, unlike the
216/// kernel's `copy_from_user`, so using `MemoryAccess::read_value` alone would
217/// turn an `EFAULT` from a raw signal syscall into success. An invalid `how`
218/// value makes `rt_sigprocmask` copy exactly the kernel-sized input and then
219/// return `EINVAL` without changing the mask. Use that as a permission probe,
220/// then read the already-validated word while the guest is stopped.
221/// The x86-64 System V red zone below the stack pointer, which a leaf function
222/// may use and an injected call therefore must not.
223pub(super) const STACK_RED_ZONE: usize = 128;
224
225/// The two eight-byte scratch cells `handle_rt_sigsuspend` places below the
226/// red zone: the rt_sigpending result and the copy of the call's mask.
227const SCRATCH_CELLS_SIZE: usize = 2 * std::mem::size_of::<u64>();
228
229pub(super) async fn read_kernel_sigset<G, T>(
230    guest: &mut G,
231    address: Addr<'_, libc::sigset_t>,
232) -> Result<KernelSigset, Error>
233where
234    G: Guest<Detcore<T>>,
235    T: RecordOrReplay,
236{
237    let validation = syscalls::RtSigprocmask::new()
238        .with_how(-1)
239        .with_set(Some(address))
240        .with_oldset(None)
241        .with_sigsetsize(KERNEL_SIGSET_SIZE);
242    match guest.inject(validation).await {
243        Err(Errno::EINVAL) => {}
244        Err(errno) => return Err(errno.into()),
245        Ok(_) => {
246            // Both Linux and the KVM syscall implementation reject an unknown
247            // operation. Success means the backend did not validate the probe.
248            return Err(Errno::EIO.into());
249        }
250    }
251    Ok(guest.memory().read_value(address.cast())?)
252}
253
254/// Whether a thread-directed SIGKILL (`tgkill` or `tkill`) names `tid`, a
255/// thread-group leader that has exited while a sibling runs on. Linux keeps
256/// such a leader as a zombie, and a SIGKILL that names it does not end its
257/// group: `complete_signal` finds that the exiting leader does not want the
258/// signal, and a thread-directed signal goes to no other thread. So the send
259/// is not reserved as a group kill; it takes the ordinary path, and the
260/// kernel answers it as Linux does, with no effect. Only a leader the
261/// scheduler retired at its own `exit` counts: it commits no other turn until
262/// the kernel shows such a leader a zombie, so by this turn it is one, in
263/// every run (`Scheduler::names_a_retired_exited_leader`). A leader that left
264/// the scheduler at a host-timed deregistration, as on DBT, does not
265/// (https://github.com/rrnewton/hermit/issues/4445).
266pub(crate) async fn sigkill_names_an_exited_leader<G, T>(guest: &mut G, tid: DetTid) -> bool
267where
268    G: Guest<Detcore<T>>,
269    T: RecordOrReplay,
270{
271    names_a_retired_exited_leader(guest, tid).await
272}
273
274/// Signal phase 1: the guest's SIGALRM disposition (a guest handler or not)
275/// and SIGALRM blocked bit, as its runtime keeps them virtual, read back with
276/// a query `rt_sigaction` and `rt_sigprocmask` that the runtime answers from
277/// its virtual state.
278async fn virtual_sigalrm_state<G, T>(guest: &mut G) -> Result<(bool, bool), Error>
279where
280    G: Guest<Detcore<T>>,
281    T: RecordOrReplay,
282{
283    let state = read_sigalrm_sleep_state(guest).await?;
284    Ok((
285        state.disposition == SigalrmSleepDisposition::Handled,
286        state.blocked,
287    ))
288}
289
290/// Query through the runtime, which reports the guest's action and mask even
291/// when it owns a physical SIGALRM handler. These queries run in an owned turn;
292/// a scheduler-side read of the callback's physical mask is not a substitute.
293async fn read_sigalrm_sleep_state<G, T>(guest: &mut G) -> Result<InGuestSleepSigalrm, Error>
294where
295    G: Guest<Detcore<T>>,
296    T: RecordOrReplay,
297{
298    let mut stack = guest.stack().await;
299    let action = stack.reserve::<KernelSigaction>();
300    let mask = stack.reserve::<KernelSigset>();
301    let _stack_guard = stack.commit()?;
302    guest
303        .inject(
304            syscalls::RtSigaction::new()
305                .with_signum(libc::SIGALRM)
306                .with_action(None)
307                .with_old_action(Some(action.cast()))
308                .with_sigsetsize(KERNEL_SIGSET_SIZE),
309        )
310        .await?;
311    guest
312        .inject(
313            syscalls::RtSigprocmask::new()
314                .with_how(libc::SIG_BLOCK)
315                .with_set(None)
316                .with_oldset(Some(mask.cast()))
317                .with_sigsetsize(KERNEL_SIGSET_SIZE),
318        )
319        .await?;
320    let action: KernelSigaction = guest.memory().read_value(action)?;
321    let mask: KernelSigset = guest.memory().read_value(mask)?;
322    let disposition = if action.handler == libc::SIG_DFL as u64 {
323        SigalrmSleepDisposition::Default
324    } else if action.handler == libc::SIG_IGN as u64 {
325        SigalrmSleepDisposition::Ignored
326    } else {
327        SigalrmSleepDisposition::Handled
328    };
329    Ok(InGuestSleepSigalrm {
330        disposition,
331        blocked: mask & kernel_sigset_bit(libc::SIGALRM) != 0,
332    })
333}
334
335/// Take one pending copy of `signo` from the calling thread's queues, its own
336/// first and then its process's shared one, as Linux dequeues it, with a
337/// zero-timeout `rt_sigtimedwait` injected while the thread holds its turn.
338/// Returns the signal taken, or the call's error (EAGAIN: none was pending).
339pub(crate) async fn take_pending_signal<G, T>(guest: &mut G, signo: i32) -> Result<i64, Error>
340where
341    G: Guest<Detcore<T>>,
342    T: RecordOrReplay,
343{
344    let mut stack = guest.stack().await;
345    let set = stack.push(kernel_sigset_bit(signo));
346    let timeout = stack.push(Timespec {
347        tv_sec: 0,
348        tv_nsec: 0,
349    });
350    let stack_guard = stack.commit()?;
351    // SAFETY: the kernel only reads the set; Reverie types the argument as
352    // mutable.
353    let set = unsafe { set.cast::<libc::sigset_t>().into_mut() };
354    let taken = guest
355        .inject(
356            syscalls::RtSigtimedwait::new()
357                .with_set(Some(set))
358                .with_info(None)
359                .with_timeout(Some(timeout))
360                .with_sigsetsize(KERNEL_SIGSET_SIZE),
361        )
362        .await;
363    drop(stack_guard);
364    Ok(taken?)
365}
366
367/// Claim a pending `SIGCHLD` for the calling thread, in its own turn, so that
368/// it is delivered to this thread as it next resumes and no other thread can
369/// take it. Returns whether there was one.
370///
371/// A harmless `getpid` is injected. Reverie runs an injected call by stepping
372/// the thread through user mode, so while a signal is pending and unblocked the
373/// kernel dequeues it at that step, Reverie holds it for delivery as the thread
374/// resumes, and the injection returns a restart errno instead of running. The
375/// caller calls this only while SIGCHLD is the signal the kernel dequeues next,
376/// so that held signal is the copy: claimed. If an outside thread took the copy
377/// first, nothing is pending, the call runs, and nothing is claimed. The call
378/// consumes no signal itself, so a stop that ends it can lose nothing (the Codex
379/// review of a version that took the copy with `rt_sigtimedwait` and queued it
380/// again).
381pub(crate) async fn claim_pending_sigchld<G, T>(guest: &mut G) -> Result<bool, Error>
382where
383    G: Guest<Detcore<T>>,
384    T: RecordOrReplay,
385{
386    match guest.inject(syscalls::Getpid::new()).await {
387        Ok(_) => Ok(false),
388        Err(errno) if is_restart_errno(errno) => Ok(true),
389        Err(errno) => Err(errno.into()),
390    }
391}
392
393/// Test-only fault hook, like `HERMIT_TEST_TIMERFD_FAULT`, acting once per run
394/// at the first claim of a `SIGCHLD` (`claim_pending_sigchld`), for the orders
395/// of https://github.com/rrnewton/hermit/issues/4346 that host timing alone
396/// gives too rarely to test:
397/// - `usr1-before-claim`: just before the claim, Detcore sends the claiming
398///   thread SIGUSR1 from its own process (an injected send would itself
399///   dequeue the pending SIGCHLD), so the thread's own queue holds a lower
400///   signal and the claim takes SIGUSR1 instead;
401/// - `usr1-after-claim`: just after the claim, Detcore sends the claiming
402///   thread SIGUSR1, which a guest that blocks it leaves pending, so the
403///   backend passes the claimed SIGCHLD on unreported;
404/// - `drop-claimed`: the claimed copy is dropped, as the ledger drops a
405///   duplicate (`Detcore::child_exit_sigchld_delivers`), at its delivery stop
406///   or where the backend passes it on unreported
407///   (`Tool::filter_unreported_signal`), so no handler runs and the sleep
408///   restarts: a relative `nanosleep` through the kernel's `restart_syscall`
409///   (`helpers::RestartCall::Nanosleep`).
410///
411/// Unset, nothing changes.
412const CLAIM_FAULT_ENV: &str = "HERMIT_TEST_SIGCHLD_CLAIM_FAULT";
413
414/// Whether the claim fault hook has fired in this process. It fires once.
415static CLAIM_FAULT_FIRED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
416
417/// A fault `HERMIT_TEST_SIGCHLD_CLAIM_FAULT` asks for.
418#[derive(Clone, Copy, Debug, PartialEq, Eq)]
419pub(crate) enum ClaimFault {
420    Usr1BeforeClaim,
421    Usr1AfterClaim,
422    DropClaimed,
423}
424
425/// Whether the hook asks for `fault` now: at most once per process.
426pub(crate) fn take_claim_fault(fault: ClaimFault) -> bool {
427    let asked = match std::env::var(CLAIM_FAULT_ENV).as_deref() {
428        Ok("usr1-before-claim") => ClaimFault::Usr1BeforeClaim,
429        Ok("usr1-after-claim") => ClaimFault::Usr1AfterClaim,
430        Ok("drop-claimed") => ClaimFault::DropClaimed,
431        _ => return false,
432    };
433    asked == fault && !CLAIM_FAULT_FIRED.swap(true, std::sync::atomic::Ordering::SeqCst)
434}
435
436/// For `usr1-before-claim` or `usr1-after-claim` (`fault`,
437/// `take_claim_fault`): send the claiming thread SIGUSR1 from Detcore's
438/// process, which shares the guest's pid namespace.
439fn send_claim_fault_signal<G, T>(guest: &G, fault: ClaimFault)
440where
441    G: Guest<Detcore<T>>,
442    T: RecordOrReplay,
443{
444    if take_claim_fault(fault) {
445        // SAFETY: tgkill only sends a signal.
446        let sent = unsafe {
447            libc::syscall(
448                libc::SYS_tgkill,
449                guest.pid().as_raw(),
450                guest.tid().as_raw(),
451                libc::SIGUSR1,
452            )
453        };
454        if sent == 0 {
455            tracing::warn!("claim fault hook: sent SIGUSR1 {:?}", fault);
456        } else {
457            tracing::error!(
458                "claim fault hook: could not send SIGUSR1 {:?}: {}",
459                fault,
460                std::io::Error::last_os_error()
461            );
462        }
463    }
464}
465
466/// Whether `errno` is a restart errno, which an injection returns when a signal
467/// stop ended it before it ran (`claim_pending_sigchld`).
468fn is_restart_errno(errno: Errno) -> bool {
469    matches!(
470        errno,
471        Errno::ERESTARTSYS
472            | Errno::ERESTARTNOINTR
473            | Errno::ERESTARTNOHAND
474            | Errno::ERESTART_RESTARTBLOCK
475    )
476}
477
478/// The guest's virtual SIGALRM blocked bit, read from the runtime (which
479/// answers the query from its virtual state).
480pub(crate) async fn virtual_sigalrm_blocked<G, T>(guest: &mut G) -> Result<bool, Error>
481where
482    G: Guest<Detcore<T>>,
483    T: RecordOrReplay,
484{
485    let mut stack = guest.stack().await;
486    let mask = stack.reserve::<KernelSigset>();
487    let _stack_guard = stack.commit()?;
488    guest
489        .inject(
490            syscalls::RtSigprocmask::new()
491                .with_how(libc::SIG_BLOCK)
492                .with_set(None)
493                .with_oldset(Some(mask.cast()))
494                .with_sigsetsize(KERNEL_SIGSET_SIZE),
495        )
496        .await?;
497    let mask: KernelSigset = guest.memory().read_value(mask)?;
498    Ok(mask & kernel_sigset_bit(libc::SIGALRM) != 0)
499}
500
501/// Validate the entire action through the kernel before copying it privately.
502/// A partial `read_value` can fall back to ptrace for its final eight bytes,
503/// which would read through a protected page. SIGKILL accepts no new action,
504/// but both Linux and KVM copy the complete input before rejecting it.
505async fn read_kernel_sigaction<G, T>(
506    guest: &mut G,
507    address: Addr<'_, libc::sigaction>,
508) -> Result<KernelSigaction, Error>
509where
510    G: Guest<Detcore<T>>,
511    T: RecordOrReplay,
512{
513    let validation = syscalls::RtSigaction::new()
514        .with_signum(libc::SIGKILL)
515        .with_action(Some(address))
516        .with_old_action(None)
517        .with_sigsetsize(KERNEL_SIGSET_SIZE);
518    match guest.inject(validation).await {
519        Err(Errno::EINVAL) => {}
520        Err(errno) => return Err(errno.into()),
521        Ok(_) => return Err(Errno::EIO.into()),
522    }
523    Ok(guest.memory().read_value(address.cast())?)
524}
525
526// AUTONOMOUS-BOT-IMPLEMENTED
527// TODO-HUMAN-REVIEW(#663)
528fn timeval_to_logical_time(value: libc::timeval) -> Result<LogicalTime, Errno> {
529    let seconds = u64::try_from(value.tv_sec).map_err(|_| Errno::EINVAL)?;
530    let micros = u64::try_from(value.tv_usec).map_err(|_| Errno::EINVAL)?;
531    if micros >= 1_000_000 {
532        return Err(Errno::EINVAL);
533    }
534    let nanos = seconds
535        .checked_mul(1_000_000_000)
536        .and_then(|nanos| nanos.checked_add(micros * 1_000))
537        .ok_or(Errno::EINVAL)?;
538    Ok(LogicalTime::from_nanos(nanos))
539}
540
541// AUTONOMOUS-BOT-IMPLEMENTED
542// TODO-HUMAN-REVIEW(#663)
543fn logical_time_to_timeval(value: LogicalTime) -> libc::timeval {
544    libc::timeval {
545        tv_sec: value.as_secs() as libc::time_t,
546        tv_usec: value.subsec_micros() as libc::suseconds_t,
547    }
548}
549
550// AUTONOMOUS-BOT-IMPLEMENTED
551// TODO-HUMAN-REVIEW(#663)
552fn logical_time_to_alarm_seconds(value: LogicalTime) -> i64 {
553    value.as_nanos().div_ceil(1_000_000_000) as i64
554}
555
556/// `alarm()`'s return as Linux computes it (`alarm_setitimer`,
557/// `kernel/time/itimer.c`): the whole seconds left, plus one when the
558/// remainder is at least half a second, or when no whole second is left but
559/// the timer is still active. So an active timer, even one with less than a
560/// microsecond left, returns at least 1
561/// (https://github.com/rrnewton/hermit/issues/4139).
562fn linux_alarm_seconds(value: LogicalTime) -> i64 {
563    let ns = value.as_nanos();
564    let (secs, rem) = (ns / 1_000_000_000, ns % 1_000_000_000);
565    let round_up = (secs == 0 && rem != 0) || rem >= 500_000_000;
566    (secs + u64::from(round_up)) as i64
567}
568
569// AUTONOMOUS-BOT-IMPLEMENTED
570// TODO-HUMAN-REVIEW(#663)
571/// A pid no task can have: above the largest `pid_max` Linux allows (2^22).
572/// `rt_sigqueueinfo` to it makes the kernel check the siginfo exactly as for
573/// any pid and then answer ESRCH, which is Linux's answer for a gone process
574/// (<https://github.com/rrnewton/hermit/issues/4124>).
575pub(crate) const NO_SUCH_PID: libc::pid_t = libc::pid_t::MAX;
576
577/// The 128 siginfo bytes at `info`. A page the kernel may write a siginfo to
578/// can lack read permission (`PROT_WRITE` alone), which `process_vm_readv`
579/// refuses; the tracer then reads it through `/proc/<tid>/mem`, as ptrace
580/// access does, which needs no read permission on the mapping.
581/// The siginfo a guest's send `call` of `signal` queues, as the receiver
582/// sees it (4262 design N8-5): the first 48 bytes of the caller's
583/// `siginfo_t` for `rt_sigqueueinfo` and `rt_tgsigqueueinfo`, or Linux's
584/// `SI_USER` (`kill`) or `SI_TKILL` (`tgkill`, `tkill`) record with the
585/// caller's process id and real uid; for `pidfd_send_signal`, the caller's
586/// siginfo or `SI_USER`. `None` when it cannot be read, or for a call
587/// Detcore does not decode, which the scheduler records as `SI_USER`.
588/// The process id is the container's, which is the receiver's unless either
589/// is in a nested PID namespace.
590fn sent_siginfo<T, G: Guest<Detcore<T>>>(
591    guest: &mut G,
592    call: &syscalls::Syscall,
593    signal: i32,
594) -> Option<KernelSiginfo>
595where
596    T: RecordOrReplay,
597{
598    if !crate::scheduler::discarded_at_send::records(guest.config()) {
599        return None;
600    }
601    let code = match call {
602        syscalls::Syscall::RtSigqueueinfo(call) => {
603            return read_siginfo(guest, call.siginfo()?)
604                .map(|bytes| KernelSiginfo::from_user(&bytes));
605        }
606        syscalls::Syscall::RtTgsigqueueinfo(call) => {
607            return read_siginfo(guest, call.siginfo()?)
608                .map(|bytes| KernelSiginfo::from_user(&bytes));
609        }
610        // `pidfd_send_signal` queues the caller's siginfo when it passes one,
611        // and Linux's `SI_USER` record otherwise.
612        syscalls::Syscall::Other(sysno, args) if *sysno == Sysno::pidfd_send_signal => {
613            match AddrMut::<libc::siginfo_t>::from_raw(args.arg2) {
614                Some(info) => {
615                    return read_siginfo(guest, info).map(|bytes| KernelSiginfo::from_user(&bytes));
616                }
617                None => libc::SI_USER,
618            }
619        }
620        syscalls::Syscall::Kill(_) => libc::SI_USER,
621        syscalls::Syscall::Tgkill(_) | syscalls::Syscall::Tkill(_) => libc::SI_TKILL,
622        _ => return None,
623    };
624    let pid = guest.thread_state().detpid?.as_raw();
625    let uid = crate::syscalls::real_uid(guest.tid().as_raw())?;
626    Some(crate::scheduler::signal_lists::ordinary_siginfo(
627        signal, code, pid, uid,
628    ))
629}
630
631fn read_siginfo<T, G: Guest<Detcore<T>>>(
632    guest: &mut G,
633    info: AddrMut<libc::siginfo_t>,
634) -> Option<[u8; 128]>
635where
636    T: RecordOrReplay,
637{
638    if let Ok(bytes) = guest.memory().read_value(info.cast::<[u8; 128]>()) {
639        return Some(bytes);
640    }
641    use std::os::unix::fs::FileExt;
642    let mem = std::fs::File::open(format!("/proc/{}/mem", guest.tid().as_raw())).ok()?;
643    let mut bytes = [0u8; 128];
644    mem.read_exact_at(&mut bytes, info.as_raw() as u64).ok()?;
645    Some(bytes)
646}
647
648/// The first bytes of the guest range at `address`, up to `len`, that are
649/// mapped: read a page at a time, through `/proc/<tid>/mem` where the page
650/// lacks read permission (`PROT_WRITE` alone, or `PROT_NONE`), and stopping at
651/// the first page that is not mapped. The kernel's copy to user mode stops at
652/// the first byte it cannot write, so every byte it can change in the range
653/// is in this prefix (the Codex re-check of
654/// https://github.com/rrnewton/hermit/pull/4351, P2-1).
655fn read_mapped_prefix<T, G: Guest<Detcore<T>>>(guest: &mut G, address: usize, len: usize) -> Vec<u8>
656where
657    T: RecordOrReplay,
658{
659    const PAGE: usize = 4096;
660    let mut bytes = Vec::with_capacity(len);
661    let mut mem = None;
662    while bytes.len() < len {
663        let at = address + bytes.len();
664        let take = (PAGE - at % PAGE).min(len - bytes.len());
665        let mut piece = vec![0u8; take];
666        let Some(remote) = AddrMut::<u8>::from_raw(at) else {
667            break;
668        };
669        if guest.memory().read_exact(remote, &mut piece).is_err() {
670            use std::os::unix::fs::FileExt;
671            if mem.is_none() {
672                mem = std::fs::File::open(format!("/proc/{}/mem", guest.tid().as_raw())).ok();
673            }
674            let Some(file) = mem.as_ref() else {
675                break;
676            };
677            if file.read_exact_at(&mut piece, at as u64).is_err() {
678                break;
679            }
680        }
681        bytes.extend_from_slice(&piece);
682    }
683    bytes
684}
685
686/// The most a signalfd read's records can need restored: one 128-byte record
687/// for each standard signal in each of the two queues it reads (the thread's
688/// and the process's). Real-time signals, which can queue more copies, are
689/// out of scope (https://github.com/rrnewton/hermit/issues/4319).
690const SIGNALFD_CAPTURED: usize = 2 * 64 * SIGNALFD_RECORD;
691
692/// What the guest's buffers `extents` (address, length) hold, in order, up to
693/// `limit` bytes and at most `SIGNALFD_CAPTURED`, read before a signalfd read
694/// writes them, so a record that read drops can leave them as they were
695/// (`apply_signalfd_answers`). The capture stops at the first byte that is not
696/// mapped, which the read cannot write either.
697pub(crate) fn capture_signalfd_buffer<T, G: Guest<Detcore<T>>>(
698    guest: &mut G,
699    extents: &[(usize, usize)],
700    limit: usize,
701) -> Vec<u8>
702where
703    T: RecordOrReplay,
704{
705    let total: usize = extents.iter().map(|(_, len)| *len).sum();
706    let len = total.min(limit).min(SIGNALFD_CAPTURED);
707    let mut bytes = Vec::with_capacity(len);
708    for (address, length) in signalfd_extent_pieces(extents, len) {
709        let piece = read_mapped_prefix(guest, address, length);
710        let short = piece.len() < length;
711        bytes.extend_from_slice(&piece);
712        if short {
713            break;
714        }
715    }
716    bytes
717}
718
719/// Put back, in the guest's siginfo buffer at `info`, the bytes that differ
720/// from `before`, the mapped prefix of its 128 bytes before a take whose copy
721/// is dropped (`read_mapped_prefix`). Only the bytes the kernel wrote differ,
722/// and it wrote only what user mode could, so no write reaches a page user
723/// mode could not write; a buffer that ends at an unmapped page keeps its
724/// prefix as it was (the Codex re-check of
725/// https://github.com/rrnewton/hermit/pull/4351, P2-1).
726fn restore_changed_bytes<T, G: Guest<Detcore<T>>>(
727    guest: &mut G,
728    info: AddrMut<libc::siginfo_t>,
729    before: &[u8],
730) where
731    T: RecordOrReplay,
732{
733    let now = read_mapped_prefix(guest, info.as_raw(), before.len());
734    let before = &before[..now.len()];
735    let mut at = 0;
736    while at < before.len() {
737        if now[at] == before[at] {
738            at += 1;
739            continue;
740        }
741        let start = at;
742        while at < before.len() && now[at] != before[at] {
743            at += 1;
744        }
745        if let Some(address) = AddrMut::<u8>::from_raw(info.as_raw() + start) {
746            let _ = guest.memory().write_exact(address, &before[start..at]);
747        }
748    }
749}
750
751/// The thread a process-directed signal goes to. `zombie` is the process's
752/// exit state (`Scheduler::exited_process_is_zombie`). `Ok(None)` is a zombie:
753/// no live threads, but its parent can still wait for it, so Linux still finds
754/// the process and the send succeeds (https://github.com/rrnewton/hermit/issues/4091).
755fn deterministic_kill_target(
756    targets: &[DetTid],
757    zombie: Option<bool>,
758    sig: libc::c_int,
759) -> Result<Option<DetTid>, Errno> {
760    match targets {
761        [] if zombie == Some(true) => Ok(None),
762        [] => Err(Errno::ESRCH),
763        [target] => Ok(Some(*target)),
764        [target, ..] if sig == 0 => Ok(Some(*target)),
765        _ => Err(Errno::ENOSYS),
766    }
767}
768
769// AUTONOMOUS-BOT-IMPLEMENTED
770// TODO-HUMAN-REVIEW(PR-1119): Review unmaskable process-group SIGKILL forwarding.
771fn can_forward_process_group_signal(
772    pid: libc::pid_t,
773    sig: libc::c_int,
774    backend_requires_pid_translation: bool,
775) -> bool {
776    pid < -1 && sig == libc::SIGKILL && !backend_requires_pid_translation
777}
778
779/// Whether one of Linux's three ordinary signal syscalls names the calling
780/// task exactly and asks for the one signal that cannot return successfully.
781///
782/// Keep process-group and broadcast spellings out of this predicate. Even when
783/// the caller belongs to the named group, KVM can refuse a group containing a
784/// second process; reserving an exit before that refusal would strand the
785/// scheduler's terminal barrier.
786fn self_sigkill_targets_current_task(
787    signal: libc::c_int,
788    target_process: Option<DetPid>,
789    target_thread: Option<DetTid>,
790    current_process: DetPid,
791    current_thread: DetTid,
792) -> bool {
793    signal == libc::SIGKILL
794        && (target_process.is_some() || target_thread.is_some())
795        && target_process.is_none_or(|target| target == current_process)
796        && target_thread.is_none_or(|target| target == current_thread)
797}
798
799impl<T: RecordOrReplay> Detcore<T> {
800    /// Bind a supported in-guest emulated sleep to its guest disposition/mask.
801    /// Ordinary admitted creation does not share signal dispositions between
802    /// processes, and each supported in-guest process has one guest thread.
803    /// The snapshot therefore stays current until this request resumes.
804    pub(crate) async fn in_guest_sleep_sigalrm_snapshot<G: Guest<Self>>(
805        &self,
806        guest: &mut G,
807    ) -> Option<InGuestSleepSigalrm> {
808        if !self.cfg.backend.virtualizes_guest_sigalrm {
809            return None;
810        }
811        match read_sigalrm_sleep_state(guest).await {
812            Ok(state) => Some(state),
813            Err(error) => {
814                self.stop_after_in_guest_sleep_signal_loss(
815                    guest,
816                    format!("could not query its SIGALRM action/mask before sleeping: {error}"),
817                )
818                .await
819            }
820        }
821    }
822
823    /// A typed wake means the scheduler generated a one-shot SIGALRM for this
824    /// exact sleep without sending it physically. Stage it through the frozen
825    /// runtime self-signal path, which runs signal and exit callbacks before
826    /// Linux kills the process. The caller must immediately return its handler:
827    /// it must neither resume guest code nor copy nanosleep's remainder out.
828    pub(crate) async fn stage_in_guest_fatal_alarm<G: Guest<Self>>(&self, guest: &mut G) {
829        if !self.cfg.backend.virtualizes_guest_sigalrm {
830            self.stop_after_in_guest_sleep_signal_loss(
831                guest,
832                "received an in-guest fatal alarm on another backend".into(),
833            )
834            .await;
835        }
836        match read_sigalrm_sleep_state(guest).await {
837            Ok(InGuestSleepSigalrm {
838                disposition: SigalrmSleepDisposition::Default,
839                blocked: false,
840            }) => {}
841            other => {
842                self.stop_after_in_guest_sleep_signal_loss(
843                    guest,
844                    format!("its default/unblocked SIGALRM sleep snapshot changed: {other:?}"),
845                )
846                .await;
847            }
848        }
849        let call = syscalls::Tgkill::new()
850            .with_tgid(guest.pid().as_raw())
851            .with_tid(guest.tid().as_raw())
852            .with_sig(libc::SIGALRM);
853        if guest.inject(call).await != Ok(0) {
854            self.stop_after_in_guest_sleep_signal_loss(
855                guest,
856                "could not stage its default-fatal SIGALRM after a sleep wake".into(),
857            )
858            .await;
859        }
860    }
861
862    async fn stop_after_in_guest_sleep_signal_loss<G: Guest<Self>>(
863        &self,
864        guest: &mut G,
865        reason: String,
866    ) -> ! {
867        let reason = format!(
868            "thread {} cannot complete its in-guest SIGALRM sleep delivery: {reason}",
869            guest.thread_state().dettid,
870        );
871        crate::tool_global::report_determinism_loss(guest, reason).await;
872        crate::guest_log::flush_unsent();
873        match guest
874            .tail_inject(
875                syscalls::ExitGroup::new().with_status(detcore_model::HERMIT_POLICY_REFUSAL_EXIT),
876            )
877            .await {}
878    }
879
880    // AUTONOMOUS-BOT-IMPLEMENTED
881    // TODO-HUMAN-REVIEW(#663)
882    /// We send the alarms to the global scheduler to handle.
883    pub async fn handle_alarm<G: Guest<Self>>(
884        &self,
885        guest: &mut G,
886        call: syscalls::Alarm,
887    ) -> Result<i64, Error> {
888        if guest.config().sequentialize_threads {
889            let remaining = register_alarm(
890                guest,
891                LogicalTime::from_secs(call.seconds() as u64),
892                LogicalTime::ZERO,
893                Signal::SIGALRM,
894            )
895            .await;
896            // Record and replay keep the rounding they recorded with.
897            Ok(if self.cfg.recordreplay_modes {
898                logical_time_to_alarm_seconds(remaining.0)
899            } else {
900                linux_alarm_seconds(remaining.0)
901            })
902        } else {
903            info!(
904                "[dtid {}] Running without scheduler, so letting alarm call through...",
905                guest.thread_state().dettid
906            );
907            Ok(guest.inject(call).await?)
908        }
909    }
910
911    // AUTONOMOUS-BOT-IMPLEMENTED
912    // TODO-HUMAN-REVIEW(#663)
913    // TODO-HUMAN-REVIEW(#869)
914    /// Schedule a one-shot or periodic real-time interval timer on Detcore logical time.
915    pub async fn handle_setitimer<G: Guest<Self>>(
916        &self,
917        guest: &mut G,
918        call: syscalls::Setitimer,
919    ) -> Result<i64, Error> {
920        if !guest.config().sequentialize_threads {
921            info!(
922                "[dtid {}] Running without scheduler, so letting setitimer call through...",
923                guest.thread_state().dettid
924            );
925            return Ok(guest.inject(call).await?);
926        }
927        if call.which() != libc::ITIMER_REAL {
928            return Err(Error::Errno(Errno::ENOSYS));
929        }
930
931        let value = call.value().ok_or(Errno::EFAULT)?;
932        let timer: libc::itimerval = guest.memory().read_value(value)?;
933        let interval = timeval_to_logical_time(timer.it_interval)?;
934        let duration = timeval_to_logical_time(timer.it_value)?;
935        // A zero value disarms the timer, whatever its interval.
936        if duration.as_nanos() != 0 && interval.as_nanos() != 0 {
937            refuse_sigalrm(guest, SigalrmControl::ArmRecurringTimer).await?;
938        }
939        let (remaining, old_interval) =
940            register_alarm(guest, duration, interval, Signal::SIGALRM).await;
941        if let Some(old_value) = call.ovalue() {
942            let old_timer = libc::itimerval {
943                it_interval: logical_time_to_timeval(old_interval),
944                it_value: logical_time_to_timeval(remaining),
945            };
946            guest.memory().write_value(old_value, &old_timer)?;
947        }
948        Ok(0)
949    }
950
951    // AUTONOMOUS-BOT-IMPLEMENTED
952    // TODO-HUMAN-REVIEW(PR-892)
953    /// Return interval-timer state from Detcore's logical scheduler.
954    pub async fn handle_getitimer<G: Guest<Self>>(
955        &self,
956        guest: &mut G,
957        call: syscalls::Getitimer,
958    ) -> Result<i64, Error> {
959        if !guest.config().sequentialize_threads {
960            info!(
961                "[dtid {}] Running without scheduler, so letting getitimer call through...",
962                guest.thread_state().dettid
963            );
964            return Ok(guest.inject(call).await?);
965        }
966
967        let snapshot = match call.which() {
968            libc::ITIMER_REAL => alarm_remaining(guest).await,
969            libc::ITIMER_VIRTUAL | libc::ITIMER_PROF => {
970                crate::scheduler::real_timer::ItimerSnapshot::default()
971            }
972            _ => return Err(Errno::EINVAL.into()),
973        };
974        let value = call.value().ok_or(Errno::EFAULT)?;
975        let timer = libc::itimerval {
976            it_interval: logical_time_to_timeval(snapshot.interval),
977            it_value: logical_time_to_timeval(snapshot.remaining),
978        };
979        guest.memory().write_value(value, &timer)?;
980        Ok(0)
981    }
982
983    /// A pause is really just an unbounded sleep.
984    pub async fn handle_pause<G: Guest<Self>>(
985        &self,
986        guest: &mut G,
987        call: syscalls::Pause,
988    ) -> Result<i64, Error> {
989        if guest.config().sequentialize_threads {
990            // `pause` has no deadline: it returns only when a signal is delivered.
991            // `LogicalTime::INDEFINITE` records that, and the scheduler refuses to
992            // fast-forward virtual time onto it (see `step2d_handle_empty_queue`),
993            // so the `Normal` arm below stays unreachable.
994            loop {
995                // A signal that already ended the call before it parked: one sent
996                // while this thread was stopped short of filing the request, as
997                // when its timeslice ended in the syscall's prehook.
998                if sleep_signal(guest, SleepCheck::BeforePark, true).await? == SleepSignal::Pending
999                {
1000                    return Err(Errno::ERESTARTNOHAND.into());
1001                }
1002                let mut req = Self::sleep_request_abs(guest, LogicalTime::INDEFINITE).await;
1003                req.fyi(crate::resources::PAUSE_FYI);
1004                req.in_guest_sleep_sigalrm = self.in_guest_sleep_sigalrm_snapshot(guest).await;
1005                match crate::tool_global::parked_wait_request(
1006                    guest,
1007                    req,
1008                    crate::scheduler::parked::ParkedWaitPolicy::PauseNoHandlerRestart,
1009                )
1010                .await
1011                {
1012                    ResumeStatus::InGuestFatalAlarm => {
1013                        self.stage_in_guest_fatal_alarm(guest).await;
1014                        return Err(Errno::EINTR.into());
1015                    }
1016                    // A pause never asks for `NothingElseCanRun`.
1017                    ResumeStatus::Normal | ResumeStatus::NothingElseCanRun => {
1018                        panic!(
1019                            "Internal violation: pause should never return from the scheduler except by interruption!"
1020                        )
1021                    }
1022                    ResumeStatus::Signaled(signals) => {
1023                        match sleep_signal(guest, SleepCheck::AfterWake(signals), true).await? {
1024                            SleepSignal::Pending | SleepSignal::Claimed => {
1025                                return Err(Errno::ERESTARTNOHAND.into());
1026                            }
1027                            SleepSignal::Held => return Err(Errno::EINTR.into()),
1028                            SleepSignal::None => {
1029                                info!(
1030                                    "[dtid {}] pause woken for a signal no longer pending for it; waiting again",
1031                                    guest.thread_state().dettid
1032                                );
1033                            }
1034                        }
1035                    }
1036                }
1037            }
1038        } else {
1039            info!(
1040                "[dtid {}] Running without scheduler, so letting pause call through...",
1041                guest.thread_state().dettid
1042            );
1043            Ok(guest.inject(call).await?)
1044        }
1045    }
1046
1047    /// Run rt_sigsuspend, without holding the deterministic scheduler turn where
1048    /// the call sleeps.
1049    ///
1050    /// The kernel must perform the temporary mask swap atomically and restore the
1051    /// original mask after signal delivery, so execute the real blocking syscall
1052    /// while marking this thread as blocked outside the runnable set.
1053    ///
1054    /// On a backend whose `rt_sigsuspend` never sleeps
1055    /// (`rt_sigsuspend_never_sleeps`: KVM), the call instead runs in the
1056    /// caller's own turn, and a refused wait yields the turn
1057    /// (<https://github.com/rrnewton/hermit/issues/4360>).
1058    pub async fn handle_rt_sigsuspend<G: Guest<Self>>(
1059        &self,
1060        guest: &mut G,
1061        call: syscalls::RtSigsuspend,
1062    ) -> Result<i64, Error> {
1063        // Invalid arguments return immediately from the kernel and therefore are
1064        // not signal-only waits.
1065        validate_kernel_sigset_size(call.sigsetsize())?;
1066        let Some(mask_addr) = call.mask() else {
1067            return Err(Errno::EFAULT.into());
1068        };
1069
1070        let temporary_mask =
1071            restart_if_first_probe_not_run(read_kernel_sigset(guest, mask_addr).await)?;
1072        super::signal_shadow::note_wait_mask(guest, temporary_mask);
1073        // The temporary mask lets the kernel take a pending real-time timer
1074        // expiration that every thread blocked when it expired
1075        // (https://github.com/rrnewton/hermit/issues/4089).
1076        observe_under_mask(guest, temporary_mask).await?;
1077        // The real call sleeps under a private copy of the mask read here, not
1078        // under the guest's buffer. The scheduler decides from this copy which
1079        // signals can end the call (`Resources::blocked_signal_mask`), and
1080        // another process sharing the buffer (MAP_SHARED) may rewrite it before
1081        // the call runs; Linux copies the mask when the call starts, and from
1082        // the guest's view the call has already started.
1083        //
1084        // The copy and the rt_sigpending result live in two cells just below
1085        // the stack's red zone, the scratch area an injected call may use, but
1086        // never on the caller's buffer: a guest may keep its mask there while
1087        // it blocks every signal, and a copy placed on that very buffer would
1088        // be the original again, while the pending cell would overwrite the
1089        // guest's mask. If the buffer overlaps the two cells, they move to just
1090        // below it. They are written directly rather than through a scratch
1091        // stack, whose commit writes one contiguous region down from the red
1092        // zone and so would cover a buffer inside it.
1093        let caller_mask = mask_addr.as_raw()..mask_addr.as_raw() + KERNEL_SIGSET_SIZE;
1094        let below_red_zone = (guest.regs().await.rsp as usize).wrapping_sub(STACK_RED_ZONE);
1095        let cells = (below_red_zone - SCRATCH_CELLS_SIZE)..below_red_zone;
1096        let cells_start = if cells.start < caller_mask.end && caller_mask.start < cells.end {
1097            (caller_mask.start - SCRATCH_CELLS_SIZE) & !(std::mem::align_of::<u64>() - 1)
1098        } else {
1099            cells.start
1100        };
1101        let pending_addr = Addr::<u64>::from_raw(cells_start).ok_or(Errno::EFAULT)?;
1102        let mask_copy = AddrMut::<u64>::from_raw(cells_start + std::mem::size_of::<u64>())
1103            .ok_or(Errno::EFAULT)?;
1104        guest.memory().write_value(mask_copy, &temporary_mask)?;
1105        let pending_out = AddrMut::<libc::sigset_t>::from_raw(pending_addr.as_raw())
1106            .expect("stack address must be non-null");
1107        let pending_call = syscalls::RtSigpending::new()
1108            .with_set(Some(pending_out))
1109            .with_sigsetsize(KERNEL_SIGSET_SIZE);
1110        guest.inject_with_retry(pending_call).await?;
1111        let pending: u64 = guest.memory().read_value(pending_addr)?;
1112        let call = call.with_mask(Some(Addr::from_raw(mask_copy.as_raw()).expect("non-null")));
1113
1114        // On a backend whose `rt_sigsuspend` never sleeps
1115        // (`rt_sigsuspend_never_sleeps`), the call returns at once, so it runs
1116        // in this thread's own turn, as any call that cannot block does.
1117        // Backgrounded as a sleeper, it left nothing holding the scheduler
1118        // between the background grant and its continuation, so the scheduler
1119        // reported a deadlock or skipped virtual time to a timed waiter, as
1120        // host timing decided (https://github.com/rrnewton/hermit/issues/4360).
1121        //
1122        // The backend refuses a wait for a signal not yet pending (ENOSYS), and
1123        // a guest retries it, so that refusal hands the turn on first with a
1124        // strong yield (`ResourceID::SchedYield`): the caller is not selected
1125        // again until another thread has had a turn, and under chaos not until
1126        // a thread that did not yield has (a yield epoch), so the threads it
1127        // waits on run before it retries, in the order the scheduler gives. In
1128        // its own turn alone, the caller spun and never let its child's exit
1129        // be granted; a weak yield, which `sched_yield` makes under chaos,
1130        // would let a caller in a higher band win every turn (the Codex
1131        // review).
1132        if rt_sigsuspend_never_sleeps(&self.cfg.backend) {
1133            let result = self.record_or_replay(guest, call).await;
1134            if result == Err(Errno::ENOSYS) && self.cfg.sequentialize_threads {
1135                if self.cfg.max_timeslice.is_some() {
1136                    guest
1137                        .thread_state_mut()
1138                        .reset_timeslice_for_explicit_yield();
1139                }
1140                let request = Self::sched_yield_request(guest);
1141                resource_request(guest, request).await;
1142            }
1143            return Ok(result?);
1144        }
1145        // The scheduler records the mask the call sleeps under, read here in
1146        // this thread's turn, to choose a SIGCHLD target while the thread is
1147        // outside the runnable set (`Resources::blocked_signal_mask`).
1148        let installed_mask = kernel_installed_signal_mask(temporary_mask);
1149        if pending & !temporary_mask != 0 {
1150            // The kernel will consume an already-pending signal as soon as it
1151            // atomically installs the temporary mask. Keep this immediate case
1152            // out of the terminal-wait classification; the real syscall still
1153            // performs delivery and restores the old mask.
1154            self.record_or_replay_blocking_with_mask(guest, call.into(), Some(installed_mask))
1155                .await
1156        } else {
1157            self.record_or_replay_rt_sigsuspend(guest, call, installed_mask)
1158                .await
1159        }
1160    }
1161
1162    /// rt_sigaction
1163    pub async fn handle_rt_sigaction<G: Guest<Self>>(
1164        &self,
1165        guest: &mut G,
1166        call: syscalls::RtSigaction,
1167    ) -> Result<i64, Error> {
1168        // Linux rejects an invalid size before inspecting either user pointer.
1169        // Preserve that EINVAL-before-EFAULT ordering even for the signal that
1170        // Hermit reserves for deterministic preemption.
1171        validate_kernel_sigset_size(call.sigsetsize())?;
1172
1173        // Copy the complete kernel object before inspecting the signal number or
1174        // writing old_action. This preserves Linux's action-before-old_action
1175        // pointer ordering, including when both arguments alias.
1176        let kernel_action = match call.action() {
1177            Some(action) => Some(restart_if_first_probe_not_run(
1178                read_kernel_sigaction(guest, action).await,
1179            )?),
1180            None => None,
1181        };
1182
1183        // SIGTRAP is reported here, at the one point where the guest states its
1184        // expectation: it falls through to the ordinary path below (its handler
1185        // really is installed; ptrace just eats the signal).
1186        // SIGSTKFLT's disposition is not installed at all; the branch below
1187        // announces that once per run instead.
1188        if let Some(action) = kernel_action
1189            && call.signum() != reverie::PERF_EVENT_SIGNAL as i32
1190        {
1191            warn_appropriated_signal(call.signum(), action.handler);
1192        }
1193
1194        // PERF_EVENT_SIGNAL is reserved.
1195        if call.signum() == reverie::PERF_EVENT_SIGNAL as i32 {
1196            // A kept fake success, announced: once per run, the coordinator
1197            // names the signal and says the disposition was not installed.
1198            if kernel_action.is_some_and(|action| action.handler != libc::SIG_DFL as u64) {
1199                crate::tool_global::announce_signal_handler_not_installed(guest, call.signum())
1200                    .await;
1201            }
1202            // The go runtime attempts to register this (unused) signal handler.  We will never
1203            // deliver signals of this kind to the guest, so we just turn this action into a noop
1204            // rather than returning `Err(Errno::EINVAL.into())`. Preserve that established
1205            // policy while still honoring the raw syscall's pointer accesses: the virtual old
1206            // disposition is the default action, never Reverie's private preemption handler.
1207            if call.old_action().is_some() {
1208                // SIGKILL's disposition cannot be changed by userspace, so its
1209                // query copies the same four zero words as our virtual default.
1210                // Let the kernel copy them: a short write_value can finish with
1211                // PTRACE_POKEDATA and overwrite a protected final word. This also
1212                // preserves the kernel's partial-copy effects on EFAULT without
1213                // exposing Reverie's private preemption action.
1214                return Ok(guest
1215                    .inject(call.with_signum(libc::SIGKILL).with_action(None))
1216                    .await?);
1217            }
1218            return Ok(0);
1219        }
1220        // Signal phase 1 (step I3): on a backend that keeps a handled SIGALRM
1221        // virtual, the scheduler's ledger must agree with the runtime.
1222        let phase1 = self.cfg.backend.virtualizes_guest_sigalrm
1223            && call.signum() == libc::SIGALRM
1224            && kernel_action.is_some();
1225        let was_handled = guest.thread_state().sigalrm_handled;
1226        let to_handler = kernel_action.is_some_and(|action| {
1227            action.handler != libc::SIG_DFL as u64 && action.handler != libc::SIG_IGN as u64
1228        });
1229        if phase1 {
1230            if to_handler {
1231                self.refuse_sigalrm_handler(guest).await?;
1232            } else if was_handled
1233                && kernel_action.is_some_and(|action| action.handler == libc::SIG_DFL as u64)
1234            {
1235                refuse_sigalrm(guest, SigalrmControl::HandlerToDefault).await?;
1236            }
1237        }
1238        // Whether this call moves the signal from `SIG_IGN` to an action that
1239        // does not ignore it, read before the change: Linux then re-queues a
1240        // periodic POSIX timer's ignored expiry (`posixtimer_sig_unignore`,
1241        // <https://github.com/rrnewton/hermit/issues/4293>).
1242        let unignores = crate::scheduler::discarded_at_send::records(guest.config())
1243            && (1..32).contains(&call.signum())
1244            && kernel_action.is_some_and(|action| {
1245                action.handler != libc::SIG_IGN as u64
1246                    && !(action.handler == libc::SIG_DFL as u64
1247                        && [libc::SIGCONT, libc::SIGCHLD, libc::SIGWINCH, libc::SIGURG]
1248                            .contains(&call.signum()))
1249            })
1250            && match crate::syscalls::signal_shadow::copied_dispositions_for(guest, call.signum()) {
1251                Some(copied) => copied.ignored & kernel_sigset_bit(call.signum()) != 0,
1252                None => {
1253                    crate::syscalls::threads::read_kernel_signal_state(guest.pid(), guest.tid())
1254                        .is_ok_and(|state| state.ignored & kernel_sigset_bit(call.signum()) != 0)
1255                }
1256            };
1257        let result = if let Some(kernel_action) = kernel_action {
1258            // The kernel treats `action` as input. Sanitize a private copy instead
1259            // of writing through the guest pointer: the input may be read-only,
1260            // and changing it would make the syscall wrapper observable.
1261            let mut kernel_action = kernel_action;
1262            kernel_action.mask = without_perf_event_signal(kernel_action.mask);
1263            let mut stack = guest.stack().await;
1264            let sanitized_action = stack.push(kernel_action);
1265            let _stack_guard = stack.commit()?;
1266            guest
1267                .inject(call.with_action(Some(sanitized_action.cast())))
1268                .await
1269        } else {
1270            guest.inject(call).await
1271        };
1272        super::signal_shadow::record_rt_sigaction(
1273            guest,
1274            call.signum(),
1275            kernel_action.map(|action| KernelSigaction {
1276                mask: without_perf_event_signal(action.mask),
1277                ..action
1278            }),
1279            call.old_action(),
1280            &result,
1281        );
1282        // Publish the state the runtime now holds whenever the disposition may
1283        // have changed: from a handler, or to one the runtime did not refuse.
1284        // Any result counts, since an EFAULT copying the old action out comes
1285        // after the change. A default or ignored action set while none is
1286        // handled changes nothing the scheduler records, so it costs nothing.
1287        if phase1 && (was_handled || (to_handler && result != Err(Errno::EPERM))) {
1288            self.publish_virtual_sigalrm(guest).await?;
1289        }
1290        // Linux reaps a process's children automatically at exit when its
1291        // SIGCHLD action is SIG_IGN or carries SA_NOCLDWAIT, and a signal to
1292        // such a child then finds no zombie. Mirror the new action for the
1293        // scheduler's exit model, with the same success rule as above
1294        // (https://github.com/rrnewton/hermit/issues/4091).
1295        if call.signum() == libc::SIGCHLD
1296            && guest.config().sequentialize_threads
1297            && let Some(action) = kernel_action
1298            && matches!(result, Ok(_) | Err(Errno::EFAULT))
1299        {
1300            let dettid = guest.thread_state().dettid;
1301            if let Some(process) = registered_process_of(guest, dettid).await {
1302                set_sigchld_disposition(
1303                    guest,
1304                    process,
1305                    action.handler == libc::SIG_IGN as u64,
1306                    action.flags & libc::SA_NOCLDWAIT as u64 != 0,
1307                )
1308                .await;
1309            }
1310        }
1311        // Linux flushes a pending SIGCHLD when its action becomes SIG_IGN or
1312        // SIG_DFL, which ignores it (`do_sigaction`, `sig_handler_ignored`): the
1313        // child-exit ledger's send window goes with it, in this committed turn
1314        // (https://github.com/rrnewton/hermit/issues/4126).
1315        if call.signum() == libc::SIGCHLD
1316            && guest.config().sequentialize_threads
1317            && matches!(result, Ok(_) | Err(Errno::EFAULT))
1318            && kernel_action.is_some_and(|action| {
1319                action.handler == libc::SIG_IGN as u64 || action.handler == libc::SIG_DFL as u64
1320            })
1321        {
1322            crate::tool_global::child_exit_sigchld(
1323                guest,
1324                crate::scheduler::child_exit_sigchld::ChildExitSigchldControl::Flushed,
1325            )
1326            .await;
1327        }
1328        // Linux flushes the pending instances of a signal whose disposition
1329        // becomes SIG_IGN (`do_sigaction`), among them a pending real-time timer
1330        // expiration (https://github.com/rrnewton/hermit/issues/4089).
1331        if result.is_ok()
1332            && kernel_action.is_some_and(|action| action.handler == libc::SIG_IGN as u64)
1333            && (1..=64).contains(&call.signum())
1334        {
1335            let bit = kernel_sigset_bit(call.signum());
1336            let pending = pending_real_time_among(guest, bit).await;
1337            act_on_pending_real_time(guest, pending, 0, bit).await;
1338        }
1339        // The same flush takes a `SIGEV_THREAD_ID` timer's pending copy of a
1340        // standard signal, for SIG_IGN or for SIG_DFL on a signal whose
1341        // default is to ignore it (`sig_handler_ignored`), so it no longer
1342        // counts as the timer's own (https://github.com/rrnewton/hermit/issues/4164).
1343        let ignored = |handler: u64| {
1344            handler == libc::SIG_IGN as u64
1345                || (handler == libc::SIG_DFL as u64
1346                    && [libc::SIGCONT, libc::SIGCHLD, libc::SIGWINCH, libc::SIGURG]
1347                        .contains(&call.signum()))
1348        };
1349        // The kernel reads the new action from Detcore's sanitized copy, so an
1350        // EFAULT can only come from writing `old_action`, after the new action
1351        // is installed.
1352        if (result.is_ok() || matches!(result, Err(Errno::EFAULT)))
1353            && kernel_action.is_some_and(|action| ignored(action.handler))
1354            && (1..32).contains(&call.signum())
1355            && crate::scheduler::timer_copies_recorded()
1356        {
1357            crate::tool_global::forget_thread_timer_copies(guest, call.signum()).await;
1358        }
1359        // A handler's mask decides where a POSIX timer's next entry goes when a
1360        // delivery promotes it (<https://github.com/rrnewton/hermit/issues/4262>).
1361        if crate::scheduler::discarded_at_send::records(guest.config())
1362            && (result.is_ok() || matches!(result, Err(Errno::EFAULT)))
1363            && (1..32).contains(&call.signum())
1364            && let Some(action) = kernel_action
1365        {
1366            crate::tool_global::discarded_signal(
1367                guest,
1368                DiscardedSignalControl::Handler {
1369                    signal: call.signum(),
1370                    caught: action.handler != libc::SIG_IGN as u64
1371                        && action.handler != libc::SIG_DFL as u64,
1372                    mask: action.mask,
1373                    nodefer: action.flags & libc::SA_NODEFER as u64 != 0,
1374                },
1375            )
1376            .await;
1377        }
1378        // The flush takes every pending copy of the signal from every queue of
1379        // the process, so none of them is one Linux discarded any more; and an
1380        // unignore makes a still-current periodic timer expiry a kept one
1381        // (`scheduler::discarded_at_send`).
1382        if crate::scheduler::discarded_at_send::records(guest.config())
1383            && (result.is_ok() || matches!(result, Err(Errno::EFAULT)))
1384            && (1..32).contains(&call.signum())
1385        {
1386            let signal = call.signum();
1387            if kernel_action.is_some_and(|action| ignored(action.handler)) {
1388                crate::tool_global::discarded_signal(
1389                    guest,
1390                    DiscardedSignalControl::Flushed { signal },
1391                )
1392                .await;
1393            } else if unignores {
1394                crate::tool_global::discarded_signal(
1395                    guest,
1396                    DiscardedSignalControl::Unignored { signal },
1397                )
1398                .await;
1399            }
1400        }
1401        Ok(result?)
1402    }
1403
1404    /// Signal phase 1's Detcore-side refusals of a new guest SIGALRM handler,
1405    /// each EPERM before anything changes (design section 6 and closure 5):
1406    /// threads not sequentialized (`alarm` would arm a kernel timer), a
1407    /// signalfd in the process's descriptor table, and a kernel producer of
1408    /// SIGALRM armed anywhere in the run.
1409    async fn refuse_sigalrm_handler<G: Guest<Self>>(&self, guest: &mut G) -> Result<(), Error> {
1410        if !guest.config().sequentialize_threads {
1411            return Err(Errno::EPERM.into());
1412        }
1413        // The model's own signalfds, and any the kernel's table holds that
1414        // the model labels otherwise (an inherited descriptor).
1415        let holds_signalfd = guest
1416            .thread_state()
1417            .file_metadata
1418            .lock()
1419            .expect("file metadata mutex poisoned")
1420            .file_handles
1421            .values()
1422            .any(|fd| fd.ty() == FdType::Signalfd)
1423            || crate::sigalrm_phase1::process_holds_signalfd(guest.pid().as_raw());
1424        if holds_signalfd {
1425            return Err(Errno::EPERM.into());
1426        }
1427        Ok(refuse_sigalrm(guest, SigalrmControl::InstallHandler).await?)
1428    }
1429
1430    /// Read the guest's SIGALRM disposition and blocked bit back from the
1431    /// runtime (which answers these queries from its virtual state), then
1432    /// publish them to the scheduler and record the disposition in the thread
1433    /// state, inside this call's turn.
1434    async fn publish_virtual_sigalrm<G: Guest<Self>>(&self, guest: &mut G) -> Result<(), Error> {
1435        let (handled, blocked) = virtual_sigalrm_state(guest).await?;
1436        sigalrm_refuses(guest, SigalrmControl::Publish { handled, blocked }).await;
1437        guest.thread_state_mut().sigalrm_handled = handled;
1438        guest.thread_state_mut().sigalrm_blocked_published = blocked;
1439        Ok(())
1440    }
1441
1442    /// After a guest call that may have changed its virtual mask in a process
1443    /// that handles SIGALRM, publish its SIGALRM blocked bit.
1444    async fn publish_virtual_sigalrm_blocked<G: Guest<Self>>(
1445        &self,
1446        guest: &mut G,
1447    ) -> Result<(), Error> {
1448        let blocked = virtual_sigalrm_blocked(guest).await?;
1449        sigalrm_refuses(guest, SigalrmControl::PublishBlocked(blocked)).await;
1450        guest.thread_state_mut().sigalrm_blocked_published = blocked;
1451        Ok(())
1452    }
1453
1454    // AUTONOMOUS-BOT-IMPLEMENTED
1455    // TODO-HUMAN-REVIEW(#1046): Review retrying interrupted signal-mask injections.
1456    /// rt_sigprocmask
1457    pub async fn handle_rt_sigprocmask<G: Guest<Self>>(
1458        &self,
1459        guest: &mut G,
1460        call: syscalls::RtSigprocmask,
1461    ) -> Result<i64, Error> {
1462        // The kernel checks sigsetsize before copying from either user pointer.
1463        validate_kernel_sigset_size(call.sigsetsize())?;
1464
1465        let (result, validated_set) = self.rt_sigprocmask_inner(guest, call).await;
1466        let set_not_read = matches!(validated_set, ValidatedSet::NotRun);
1467        if guest.thread_state().signal_shadow.is_some() {
1468            use super::signal_shadow::SetInput;
1469            let errno_result = match &result {
1470                Ok(value) => Some(Ok(*value)),
1471                Err(Error::Errno(errno)) => Some(Err(*errno)),
1472                Err(_) => {
1473                    super::signal_shadow::give_up(
1474                        guest,
1475                        "rt_sigprocmask failed without an errno, so its effect is unknown",
1476                    );
1477                    None
1478                }
1479            };
1480            let set = match (call.set(), validated_set) {
1481                (None, _) => SetInput::None,
1482                (Some(_), ValidatedSet::Validated(set)) => {
1483                    SetInput::Validated(without_perf_event_signal(set))
1484                }
1485                (Some(_), ValidatedSet::NotRun) => SetInput::NotRun,
1486                // Read after the call, from memory the kernel itself just
1487                // read, and only when it succeeded; an old mask written over
1488                // any of the set's bytes leaves it unknown.
1489                (Some(set), ValidatedSet::NotValidated) => SetInput::Unvalidated(
1490                    (result.is_ok()
1491                        && !call.oldset().is_some_and(|old| {
1492                            old.as_raw().abs_diff(set.as_raw()) < KERNEL_SIGSET_SIZE
1493                        }))
1494                    .then(|| {
1495                        guest
1496                            .memory()
1497                            .read_value::<_, KernelSigset>(set.cast::<KernelSigset>())
1498                            .ok()
1499                    })
1500                    .flatten()
1501                    .map(without_perf_event_signal),
1502                ),
1503            };
1504            if let Some(errno_result) = errno_result {
1505                super::signal_shadow::record_rt_sigprocmask(
1506                    guest,
1507                    call.how(),
1508                    set,
1509                    call.oldset(),
1510                    &errno_result,
1511                );
1512            }
1513        }
1514        // The set's probe did not run, and the call restarts
1515        // (`restart_if_first_probe_not_run`): nothing changed, so nothing
1516        // follows from a change; the restarted call does the rest.
1517        if set_not_read && matches!(result, Err(Error::Errno(Errno::ERESTARTNOINTR))) {
1518            return result;
1519        }
1520        if call.how() != libc::SIG_BLOCK && call.set().is_some() {
1521            // The new mask may unblock a pending real-time timer expiration
1522            // that every thread blocked when it expired, which the kernel then
1523            // delivers (https://github.com/rrnewton/hermit/issues/4089). Whatever
1524            // the call returned: an EFAULT copying the old set out comes after
1525            // the change. A mask that cannot be read could unblock any of them.
1526            let pending = pending_real_time_among(guest, REAL_TIME_SIGNALS).await;
1527            if pending != 0 {
1528                let (observable, discarded) =
1529                    match read_thread_wait_signal_state(guest.pid(), guest.tid()) {
1530                        Ok(state) => unblocked_by(&state, state.blocked),
1531                        Err(_) => (REAL_TIME_SIGNALS, 0),
1532                    };
1533                act_on_pending_real_time(guest, pending, observable, discarded).await;
1534            }
1535        }
1536        if self.cfg.backend.virtualizes_guest_sigalrm && guest.thread_state().sigalrm_handled {
1537            // Signal phase 1: the scheduler's blocked bit follows the virtual
1538            // mask, whatever the call returned (an EFAULT copying the old set
1539            // out comes after the change).
1540            self.publish_virtual_sigalrm_blocked(guest).await?;
1541        }
1542        result
1543    }
1544
1545    /// The call itself. Also says whether, and with what set, the kernel ran
1546    /// it: the `SIG_BLOCK` and `SIG_SETMASK` paths read the set through the
1547    /// kernel first and inject nothing when that fails.
1548    async fn rt_sigprocmask_inner<G: Guest<Self>>(
1549        &self,
1550        guest: &mut G,
1551        call: syscalls::RtSigprocmask,
1552    ) -> (Result<i64, Error>, ValidatedSet) {
1553        if call.how() != libc::SIG_BLOCK && call.how() != libc::SIG_SETMASK {
1554            let result = guest.inject_with_retry(call).await;
1555            (result.map_err(Into::into), ValidatedSet::NotValidated)
1556        } else if let Some(set) = call.set() {
1557            let set_mask =
1558                match restart_if_first_probe_not_run(read_kernel_sigset(guest, set).await) {
1559                    Ok(set_mask) => set_mask,
1560                    Err(error) => return (Err(error), ValidatedSet::NotRun),
1561                };
1562            let mut stack = guest.stack().await;
1563            let new_set = stack.push(without_perf_event_signal(set_mask));
1564            let _stack_guard = match stack.commit() {
1565                Ok(guard) => guard,
1566                Err(error) => return (Err(error.into()), ValidatedSet::NotRun),
1567            };
1568            let modified_call = syscalls::RtSigprocmask::new()
1569                .with_how(call.how())
1570                .with_set(Some(new_set.cast()))
1571                .with_oldset(call.oldset())
1572                .with_sigsetsize(call.sigsetsize());
1573            // Keep returning to the handler so post_handler_hook can run, but
1574            // do not expose a tracer preemption as ERESTARTSYS to the guest.
1575            let result = guest.inject_with_retry(modified_call).await;
1576            (
1577                result.map_err(Into::into),
1578                ValidatedSet::Validated(set_mask),
1579            )
1580        } else {
1581            let result = guest.inject_with_retry(call).await;
1582            (result.map_err(Into::into), ValidatedSet::NotValidated)
1583        }
1584    }
1585
1586    /// rt_sigtimedwait system call
1587    ///
1588    /// This is handled by the scheduler and not passed to the record/replay layer,
1589    /// because currently signals are not recorded.
1590    pub async fn handle_rt_sigtimedwait<G: Guest<Self>>(
1591        &self,
1592        guest: &mut G,
1593        call: syscalls::RtSigtimedwait,
1594    ) -> Result<i64, Error> {
1595        // Linux rejects an invalid mask width before inspecting its pointers.
1596        validate_kernel_sigset_size(call.sigsetsize())?;
1597        // Linux keeps this entry snapshot for the whole wait. The retry helper
1598        // currently injects from the caller's pointer again, so another thread
1599        // can change the set between retries. Fixing that requires sharing one
1600        // scratch-stack guard with the helper's zero-timeout object; do not hide
1601        // that remaining difference by treating this validation read as a snapshot.
1602
1603        let dettid = guest.thread_state().dettid;
1604
1605        let maybe_timeout = if let Some(timeout) = call.timeout() {
1606            let ts: Timespec = guest.memory().read_value(timeout)?;
1607            let ns_delta =
1608                Duration::from_secs(ts.tv_sec as u64) + Duration::from_nanos(ts.tv_nsec as u64);
1609            let base_time = thread_observe_time(guest).await;
1610            let target_time = base_time + ns_delta;
1611            Some(target_time)
1612        } else {
1613            None
1614        };
1615        let mut rsrc = Resources::new(dettid);
1616        rsrc.insert(ResourceID::InternalIOPolling, Permission::W);
1617        rsrc.fyi("rt_sigtimedwait");
1618        // While it polls, a signal in the set is taken at the next poll
1619        // whatever the thread's mask, which a process-directed signal another
1620        // thread sends must account for
1621        // (`Scheduler::own_process_signal_inputs`). An unreadable set fails in
1622        // the kernel at the first poll.
1623        let waited = match call.set() {
1624            Some(set) => {
1625                match restart_if_first_probe_not_run(read_kernel_sigset(guest, set.into()).await) {
1626                    Err(Error::Errno(Errno::ERESTARTNOINTR)) => {
1627                        return Err(Errno::ERESTARTNOINTR.into());
1628                    }
1629                    read => read.ok(),
1630                }
1631            }
1632            None => None,
1633        };
1634        if waited.is_some() {
1635            set_sigtimedwait_set(guest, waited).await;
1636        }
1637        // Linux writes the siginfo only for a signal it returns. A dropped
1638        // copy's siginfo is replaced by what the buffer held before.
1639        let records = crate::scheduler::discarded_at_send::records(guest.config());
1640        let before = match call.info() {
1641            Some(info) if self.cfg.backend.reports_child_exit_publication || records => {
1642                Some(read_mapped_prefix(guest, info.as_raw(), 128))
1643            }
1644            _ => None,
1645        };
1646        let result = loop {
1647            let result =
1648                retry_nonblocking_syscall_with_timeout(guest, call, rsrc.clone(), maybe_timeout)
1649                    .await;
1650            // A consumed child-exit copy that the notification ledger drops
1651            // is not returned: the wait goes on, to the same deadline.
1652            let stands = self
1653                .synchronous_sigchld_stands(guest, call, waited, &result)
1654                .await;
1655            // Nor is a copy Linux discarded when it was sent, which Linux never
1656            // dequeues (https://github.com/rrnewton/hermit/issues/4293). The
1657            // take went into the guest's own buffer, so the kernel made the
1658            // copy-out with its own partial-write and EFAULT rules for a kept
1659            // copy; for a dropped one, the bytes it changed are put back.
1660            let outcome = if records {
1661                self.take_outcome_of(guest, waited, &result).await
1662            } else {
1663                crate::scheduler::posix_timer_coalesce::TakeOutcome {
1664                    skip: false,
1665                    rewrite: None,
1666                }
1667            };
1668            if stands && !outcome.skip {
1669                // A POSIX timer's entry, or a kept signal standing on another
1670                // sender's record, is returned with its own siginfo
1671                // (<https://github.com/rrnewton/hermit/issues/4262>); the
1672                // kernel's copy-out succeeded, so the buffer is writable.
1673                if let (Ok(_), Some(info), Some(rewrite)) = (&result, call.info(), outcome.rewrite)
1674                    && guest
1675                        .memory()
1676                        .write_value(info.cast::<[u8; 128]>(), &rewrite.to_user())
1677                        .is_err()
1678                {
1679                    tracing::warn!(
1680                        "[dtid {}] rt_sigtimedwait's siginfo keeps the physical record",
1681                        guest.thread_state().dettid
1682                    );
1683                }
1684                break result;
1685            }
1686            if let (Some(info), Some(bytes)) = (call.info(), before.as_ref()) {
1687                restore_changed_bytes(guest, info, bytes);
1688            }
1689        };
1690        if waited.is_some() {
1691            set_sigtimedwait_set(guest, None).await;
1692        }
1693        // O2: any completion of a wait for SIGALRM may have dequeued the
1694        // process's ITIMER_REAL copy, including one that then failed copying
1695        // out the siginfo (https://github.com/rrnewton/hermit/issues/4139).
1696        if waited.is_some_and(|set| {
1697            set & crate::syscalls::threads::kernel_sigset_bit(libc::SIGALRM) != 0
1698        }) {
1699            crate::tool_global::reconcile_alarm(guest).await;
1700        }
1701        result
1702    }
1703
1704    /// What to do with the take that ended this thread's `rt_sigtimedwait`
1705    /// for the signals `waited` with `result` (`take_outcome`, from the
1706    /// queues read after it; for an EFAULT, which names no signal,
1707    /// `DiscardedSignalControl::TakeFaulted`).
1708    async fn take_outcome_of<G: Guest<Self>>(
1709        &self,
1710        guest: &mut G,
1711        waited: Option<u64>,
1712        result: &Result<i64, Error>,
1713    ) -> crate::scheduler::posix_timer_coalesce::TakeOutcome {
1714        use crate::scheduler::posix_timer_coalesce::TakeOutcome;
1715        let skip = |skip| TakeOutcome {
1716            skip,
1717            rewrite: None,
1718        };
1719        match result {
1720            Ok(signal) if (1..32).contains(&(*signal as i32)) => {
1721                let after =
1722                    crate::syscalls::threads::read_kernel_signal_state(guest.pid(), guest.tid())
1723                        .ok()
1724                        .map(|state| (state.thread_pending, state.shared_pending));
1725                crate::syscalls::helpers::take_outcome(guest, *signal as i32, after).await
1726            }
1727            Err(Error::Errno(Errno::EFAULT)) => {
1728                let Some(set) = waited else {
1729                    return skip(false);
1730                };
1731                let Ok(state) =
1732                    crate::syscalls::threads::read_kernel_signal_state(guest.pid(), guest.tid())
1733                else {
1734                    return skip(false);
1735                };
1736                let at = guest.thread_state().thread_logical_time.as_nanos();
1737                skip(matches!(
1738                    crate::tool_global::discarded_signal(
1739                        guest,
1740                        DiscardedSignalControl::TakeFaulted {
1741                            set,
1742                            thread_pending: state.thread_pending,
1743                            shared_pending: state.shared_pending,
1744                            at,
1745                        },
1746                    )
1747                    .await,
1748                    DiscardedSignalAnswer::Discarded(true)
1749                ))
1750            }
1751            _ => skip(false),
1752        }
1753    }
1754
1755    /// The `signalfd_siginfo` records a successful signalfd `read` returned,
1756    /// `len` bytes at `buf`, reconciled with the child-exit ledger
1757    /// (`reconcile_signalfd_extents`). Returns the bytes kept, or `None` to
1758    /// refuse.
1759    pub(crate) async fn reconcile_signalfd_records<G: Guest<Self>>(
1760        &self,
1761        guest: &mut G,
1762        buf: AddrMut<'_, u8>,
1763        len: usize,
1764        before: &[u8],
1765    ) -> Option<usize> {
1766        self.reconcile_signalfd_extents(guest, &[(buf.as_raw(), len)], len, before)
1767            .await
1768    }
1769
1770    /// The `signalfd_siginfo` records a successful signalfd read returned:
1771    /// the first `read` bytes of the guest buffers `extents` (address,
1772    /// length), in order, as `read`, `readv`, `preadv` and `preadv2` scatter
1773    /// them. They are reconciled with the child-exit ledger as a SIGCHLD
1774    /// delivered to a handler (`Detcore::child_exit_sigchld_delivers`) or
1775    /// consumed by `rt_sigtimedwait` (`synchronous_sigchld_stands`) is: the
1776    /// scheduler's copy gets the siginfo Linux gives the parent, the kernel's
1777    /// coalesced copy for a SIGKILL cohort names the cohort's lowest pid, and
1778    /// a copy for an exit a SIGCHLD already stood for is dropped. Other
1779    /// records are kept as read. The kept records are scattered back over the
1780    /// same extents, in order, with the bytes the buffer held before the read
1781    /// (`before`) over the bytes of dropped ones. Returns the bytes kept, a
1782    /// whole number of records, or `None` when a record is dropped whose bytes
1783    /// `before` does not cover, which the caller refuses
1784    /// (`refuse_unrestorable_signalfd_record`).
1785    pub(crate) async fn reconcile_signalfd_extents<G: Guest<Self>>(
1786        &self,
1787        guest: &mut G,
1788        extents: &[(usize, usize)],
1789        read: usize,
1790        before: &[u8],
1791    ) -> Option<usize> {
1792        let len = read - read % SIGNALFD_RECORD;
1793        let pieces = signalfd_extent_pieces(extents, len);
1794        let mut bytes = Vec::with_capacity(len);
1795        for (address, length) in &pieces {
1796            let mut piece = vec![0u8; *length];
1797            let Some(address_mut) = AddrMut::<u8>::from_raw(*address) else {
1798                return Some(len);
1799            };
1800            if guest.memory().read_exact(address_mut, &mut piece).is_err() {
1801                use std::os::unix::fs::FileExt;
1802                let read = std::fs::File::open(format!("/proc/{}/mem", guest.tid().as_raw()))
1803                    .and_then(|mem| mem.read_exact_at(&mut piece, *address as u64));
1804                if read.is_err() {
1805                    // The kernel has just written these bytes, so the buffer
1806                    // is mapped and writable; `/proc/<tid>/mem` reads any
1807                    // such page.
1808                    return Some(len);
1809                }
1810            }
1811            bytes.extend_from_slice(&piece);
1812        }
1813        let controls = signalfd_record_controls(&bytes, std::process::id());
1814        let mut answers = Vec::with_capacity(controls.len());
1815        for control in controls {
1816            answers.push(match control {
1817                Some(control) => Some(crate::tool_global::child_exit_sigchld(guest, control).await),
1818                None => None,
1819            });
1820        }
1821        // A record of a copy Linux discarded when it was sent is dropped, as a
1822        // duplicate is: the guest never sees it
1823        // (`crate::syscalls::helpers::take_was_discarded`,
1824        // <https://github.com/rrnewton/hermit/issues/4293>).
1825        // A POSIX timer's entry, or a kept signal standing on another
1826        // sender's record, gets its own record in place of the kernel's
1827        // (<https://github.com/rrnewton/hermit/issues/4262>), and a stale
1828        // timer entry is dropped as a discarded copy is.
1829        if crate::scheduler::discarded_at_send::records(guest.config()) {
1830            for (record, answer) in bytes.chunks_mut(SIGNALFD_RECORD).zip(answers.iter_mut()) {
1831                let signal = signalfd_field(record, 0) as i32;
1832                if !(1..32).contains(&signal) {
1833                    continue;
1834                }
1835                let outcome = crate::syscalls::helpers::take_outcome(guest, signal, None).await;
1836                if outcome.skip {
1837                    *answer = Some(
1838                        crate::scheduler::child_exit_sigchld::ChildExitSigchldAnswer::Claimed(true),
1839                    );
1840                } else if let Some(rewrite) = outcome.rewrite {
1841                    record.copy_from_slice(&crate::scheduler::signal_lists::signalfd_record(
1842                        &rewrite,
1843                    ));
1844                }
1845            }
1846        }
1847        let rewritten = match apply_signalfd_answers(&bytes, &answers, before) {
1848            Ok(Some(rewritten)) => rewritten,
1849            Ok(None) => return Some(len),
1850            Err(()) => return None,
1851        };
1852        let mut offset = 0;
1853        for (address, length) in &pieces {
1854            let written = AddrMut::<u8>::from_raw(*address).map(|address| {
1855                guest
1856                    .memory()
1857                    .write_exact(address, &rewritten.bytes[offset..offset + length])
1858            });
1859            if !matches!(written, Some(Ok(()))) {
1860                tracing::warn!(
1861                    "[dtid {}] the signalfd records at {:#x} keep the kernel's siginfo",
1862                    guest.thread_state().dettid,
1863                    address,
1864                );
1865                return Some(len);
1866            }
1867            offset += length;
1868        }
1869        Some(rewritten.kept)
1870    }
1871
1872    /// A child-exit SIGCHLD that a synchronous wait consumed goes through the
1873    /// same notification ledger as one delivered to a handler
1874    /// (`Detcore::child_exit_sigchld_delivers`), on a backend where both the
1875    /// kernel and the scheduler send it (`scheduler::child_exit_sigchld`).
1876    /// The scheduler's copy is returned with the siginfo Linux gives the
1877    /// parent, and a copy for an exit that a SIGCHLD already stood for is
1878    /// dropped. Returns whether the consumed signal stands.
1879    async fn synchronous_sigchld_stands<G: Guest<Self>>(
1880        &self,
1881        guest: &mut G,
1882        call: syscalls::RtSigtimedwait,
1883        waited: Option<u64>,
1884        result: &Result<i64, Error>,
1885    ) -> bool {
1886        if !self.cfg.backend.reports_child_exit_publication {
1887            return true;
1888        }
1889        // Linux copies the set in before it dequeues, and the siginfo out
1890        // after, so an EFAULT with a readable set (`waited`) took a signal it
1891        // never reports; an unreadable set dequeued nothing. Which copy it
1892        // took: a recorded private one if SIGCHLD is gone from the thread's
1893        // private queue, which only committed guest sends fill; otherwise,
1894        // with SIGCHLD the only signal in the set, the shared queue's. A wider
1895        // set falls back to the shared queue's pending bit (the Claude and
1896        // Codex re-checks of https://github.com/rrnewton/hermit/pull/4131).
1897        if matches!(result, Err(Error::Errno(Errno::EFAULT)))
1898            && guest.config().sequentialize_threads
1899            && let Some(set) = waited
1900        {
1901            let sigchld = kernel_sigset_bit(libc::SIGCHLD);
1902            if set & sigchld != 0
1903                && let Ok(state) = crate::syscalls::threads::read_thread_wait_signal_state(
1904                    guest.pid(),
1905                    guest.tid(),
1906                )
1907            {
1908                let shared_pending = if set & !sigchld == 0 {
1909                    false
1910                } else {
1911                    state.shared_pending & sigchld != 0
1912                };
1913                crate::tool_global::child_exit_sigchld(
1914                    guest,
1915                    crate::scheduler::child_exit_sigchld::ChildExitSigchldControl::WaitFaulted {
1916                        private_pending: state.thread_pending & sigchld != 0,
1917                        shared_pending,
1918                    },
1919                )
1920                .await;
1921            }
1922            return true;
1923        }
1924        if !matches!(result, Ok(signal) if *signal == libc::SIGCHLD as i64) {
1925            return true;
1926        }
1927        // Without a siginfo buffer the guest sees only the signal number,
1928        // which every copy shares; the ledger still learns that the wait took
1929        // one (`DequeuedCopy::Unknown`), which may be the shared queue's.
1930        let Some(info) = call.info() else {
1931            crate::tool_global::child_exit_sigchld(
1932                guest,
1933                crate::scheduler::child_exit_sigchld::ChildExitSigchldControl::Dequeue {
1934                    copy: crate::scheduler::child_exit_sigchld::DequeuedCopy::Unknown,
1935                    admits: false,
1936                },
1937            )
1938            .await;
1939            return true;
1940        };
1941        let Some(bytes) = read_siginfo(guest, info) else {
1942            return true;
1943        };
1944        Self::synchronous_sigchld_copy_stands(guest, info, &bytes).await
1945    }
1946
1947    /// The child-exit ledger's answer for the `SIGCHLD` with siginfo `bytes`
1948    /// that `rt_sigtimedwait` returned into `info`
1949    /// (`synchronous_sigchld_stands`).
1950    async fn synchronous_sigchld_copy_stands<G: Guest<Self>>(
1951        guest: &mut G,
1952        info: AddrMut<'_, libc::siginfo_t>,
1953        bytes: &[u8; 128],
1954    ) -> bool {
1955        use crate::scheduler::child_exit_sigchld::ChildExitSigchldAnswer;
1956        use crate::scheduler::child_exit_sigchld::OwnCopy;
1957        // Taken by the wait, a kept copy makes no `InboundSignal` request.
1958        let Some(control) =
1959            crate::scheduler::child_exit_sigchld::control_for(bytes, std::process::id(), false)
1960        else {
1961            return true;
1962        };
1963        match crate::tool_global::child_exit_sigchld(guest, control).await {
1964            ChildExitSigchldAnswer::Claimed(dropped) => !dropped,
1965            ChildExitSigchldAnswer::OwnCopy(OwnCopy::Duplicate) => false,
1966            ChildExitSigchldAnswer::OwnCopy(OwnCopy::Deliver(own))
1967            | ChildExitSigchldAnswer::ClaimedFor(own) => {
1968                if let Err(error) = guest
1969                    .memory()
1970                    .write_value(info.cast::<[u8; 128]>(), &own.to_bytes())
1971                {
1972                    tracing::warn!(
1973                        "[dtid {}] the SIGCHLD for child {} keeps its siginfo: {}",
1974                        guest.thread_state().dettid,
1975                        own.pid,
1976                        error
1977                    );
1978                }
1979                true
1980            }
1981            _ => true,
1982        }
1983    }
1984
1985    /// Fence an exact self-SIGKILL at the scheduler-selected syscall turn.
1986    ///
1987    /// This applies only when Detcore holds the backend's process signal
1988    /// control (`BackendSignalControlMode::ToolControlled`). A backend that
1989    /// installed that control commits this syscall as an immediate,
1990    /// nonreturning process exit. It therefore has no later return boundary at
1991    /// which the ordinary pending signal path could acquire a delivery permit.
1992    /// Without this preflight, the backend's terminal child callback arrives
1993    /// with no generation-bound reservation and must fail closed.
1994    /// `ResourceID::Exit` is the same fence used by `exit_group`. A run without
1995    /// the installed control (`Unchanged`, including every non-sequentialized
1996    /// run) keeps its ordinary signal path and reserves nothing.
1997    pub(crate) async fn reserve_controlled_self_sigkill_exit<G: Guest<Self>>(
1998        &self,
1999        guest: &mut G,
2000        signal: libc::c_int,
2001        target_process: Option<DetPid>,
2002        target_thread: Option<DetTid>,
2003    ) -> bool {
2004        if guest.signal_control_mode() != reverie::BackendSignalControlMode::ToolControlled {
2005            return false;
2006        }
2007        let (current_thread, mm) = {
2008            let state = guest.thread_state();
2009            (state.dettid, state.mm_id)
2010        };
2011        if !self_sigkill_targets_current_task(
2012            signal,
2013            target_process,
2014            target_thread,
2015            self.detpid,
2016            current_thread,
2017        ) {
2018            return false;
2019        }
2020        let request = guest.thread_state().mk_request(
2021            ResourceID::Exit {
2022                group: true,
2023                process: self.detpid,
2024                mm,
2025            },
2026            Permission::RW,
2027        );
2028        resource_request(guest, request).await;
2029        true
2030    }
2031
2032    /// A backend that cannot deliver a guest's signal (the KVM backend, to
2033    /// another process for example) refuses it with ENOSYS and the typed
2034    /// refusal `UnsupportedOperation::Signal`. Report that refusal by name and
2035    /// route it through the unsupported-operation policy, instead of handing
2036    /// the guest the backend's bare ENOSYS, which left a waiting parent
2037    /// deadlocked. The name goes to tracing and directly to stderr in both
2038    /// dispositions, so neither --log=off nor --log-file hides it. Callers pass
2039    /// the handler's result right after the injection that may have been
2040    /// refused: the next injection replaces the backend's record. Every other
2041    /// result passes through unchanged. No backend is named here; a backend
2042    /// that records no refusal is unaffected.
2043    pub(crate) async fn report_backend_signal_refusal<G: Guest<Self>>(
2044        &self,
2045        guest: &mut G,
2046        sysno: Sysno,
2047        result: Result<i64, Error>,
2048    ) -> Result<i64, Error> {
2049        if !matches!(result, Err(Error::Errno(Errno::ENOSYS))) {
2050            return result;
2051        }
2052        let Some(refusal) = guest
2053            .take_unsupported_refusal()
2054            .filter(|refusal| refusal.operation == reverie::UnsupportedOperation::Signal)
2055        else {
2056            return result;
2057        };
2058        let message = format!(
2059            "[dtid {}] {sysno} refused by the backend: {}. No signal was sent.",
2060            guest.thread_state().dettid,
2061            refusal.diagnostic
2062        );
2063        tracing::error!("{message}");
2064        let _ = std::io::Write::write_fmt(
2065            &mut crate::util::RetryingStderr,
2066            format_args!("hermit: {message}\n"),
2067        );
2068        if !self.cfg.panic_on_unsupported_syscalls {
2069            crate::tool_global::report_unsupported_syscall(guest, sysno).await;
2070        }
2071        self.refuse_unserviceable_operation(guest, sysno, Errno::ENOSYS)
2072            .await
2073    }
2074
2075    // AUTONOMOUS-BOT-IMPLEMENTED
2076    // TODO-HUMAN-REVIEW(#663)
2077    // TODO-HUMAN-REVIEW(PR-1058): Review process-pending signal preservation.
2078    // TODO-HUMAN-REVIEW(PR-1119): Review unmaskable process-group SIGKILL forwarding.
2079    /// Resolve signal-zero existence checks in the fixed PID namespace, then route an
2080    /// unambiguous positive-PID process signal through the backend. Backends that can execute
2081    /// with guest PIDs preserve process-directed delivery; DBT translates it to the sole live
2082    /// thread because its native process uses a host PID. An unmaskable SIGKILL to a specific
2083    /// process group is also safe to preserve on backends whose guests use real namespace PIDs;
2084    /// other process-group and broadcast delivery remains refused until Detcore models eligible
2085    /// signal masks.
2086    pub async fn handle_kill<G: Guest<Self>>(
2087        &self,
2088        guest: &mut G,
2089        call: syscalls::Kill,
2090    ) -> Result<i64, Error> {
2091        self.record_orphaned_group_signals(guest, call.sig()).await;
2092        // A thread below the container's PID namespace names pids of its own
2093        // namespace, where none of Hermit's tasks is visible
2094        // (https://github.com/rrnewton/hermit/issues/4155).
2095        let nested = guest.thread_state().nested_pid_namespace;
2096        if !guest.config().sequentialize_threads {
2097            // Without sequentialization every other kill goes to the kernel as
2098            // is, but never one to a process group or to every process: the
2099            // guest's process group is inherited from Hermit's, so it can hold
2100            // Hermit and the user's shell or test runner, which a group kill
2101            // would reach (https://github.com/rrnewton/hermit/issues/4057).
2102            // Signal 0 sends nothing, and INT_MIN is ESRCH before any lookup.
2103            if call.sig() != 0 && call.pid() <= 0 && call.pid() != libc::pid_t::MIN {
2104                return self
2105                    .refuse_group_signal(guest, call.pid(), call.sig())
2106                    .await;
2107            }
2108            if !nested
2109                && self
2110                    .drop_signal_to_hermit(guest, Sysno::kill, None, call.pid(), call.sig())
2111                    .await
2112            {
2113                return Ok(0);
2114            }
2115            return Ok(self.record_or_replay(guest, call).await?);
2116        }
2117
2118        // A nested caller's process-group ids are its namespace's, which
2119        // Detcore does not translate yet; a SIGKILL to one would otherwise be
2120        // reserved for the container's group of that number.
2121        if nested && call.pid() <= 0 && call.pid() != libc::pid_t::MIN && call.sig() != 0 {
2122            return self
2123                .refuse_group_signal(guest, call.pid(), call.sig())
2124                .await;
2125        }
2126        let (named, own_init_caught) = if call.pid() > 0 {
2127            match self.name_guest_pid(guest, Sysno::kill, call.pid()).await {
2128                NamedGuestPid::Task {
2129                    task,
2130                    own_init_caught,
2131                } => (task.as_raw(), own_init_caught),
2132                NamedGuestPid::Answer(answer) => return answer,
2133            }
2134        } else {
2135            (call.pid(), None)
2136        };
2137        if Self::own_namespace_init_drops(own_init_caught, call.sig()) {
2138            let task = DetTid::from_raw(named);
2139            return self
2140                .send_to_own_init(guest, call, task, QueueId::Process(task), call.sig())
2141                .await;
2142        }
2143
2144        // Linux's `kill_something_info` answers ESRCH for pid INT_MIN before
2145        // anything else ("-INT_MIN is undefined"), so the kernel's answer is
2146        // deterministic and sends nothing; negating it here would overflow
2147        // (https://github.com/rrnewton/hermit/issues/4046).
2148        if call.sig() == 0 && call.pid() > 0 {
2149            // An existence check answers from the same model as a signal, so
2150            // that one pid never answers 0 to one and ESRCH to the other: a
2151            // process with no live threads is a zombie (0) or gone (ESRCH)
2152            // whenever Detcore saw it exit, whatever the host has reaped by
2153            // now (https://github.com/rrnewton/hermit/issues/4091).
2154            let (targets, zombie) =
2155                resolve_kill_targets_and_exit(guest, DetPid::from_raw(named)).await;
2156            if targets.is_empty() {
2157                match zombie {
2158                    Some(true) => return Ok(0),
2159                    Some(false) => return Err(Errno::ESRCH.into()),
2160                    None => {}
2161                }
2162            }
2163        }
2164        if call.sig() == 0 || call.pid() == libc::pid_t::MIN {
2165            return Ok(self.record_or_replay(guest, call).await?);
2166        }
2167
2168        let tgid = named;
2169        // A process-group or broadcast SIGALRM is refused by name below. The
2170        // scheduler resolves a thread id to its process itself.
2171        if call.sig() == libc::SIGALRM && tgid > 0 {
2172            refuse_sigalrm(guest, SigalrmControl::SendTo(DetTid::from_raw(tgid))).await?;
2173        }
2174        if self
2175            .drop_signal_to_hermit(guest, Sysno::kill, None, tgid, call.sig())
2176            .await
2177        {
2178            return Ok(0);
2179        }
2180        if can_forward_process_group_signal(
2181            tgid,
2182            call.sig(),
2183            guest
2184                .config()
2185                .backend
2186                .requires_thread_directed_process_signals,
2187        ) {
2188            // The scheduler is not told about each killed process, but it must
2189            // know the group was killed: a held process in it will die, so a
2190            // wait for it is not part of a deadlock
2191            // (https://github.com/rrnewton/hermit/issues/3904). Told before
2192            // the kill, inside this committed turn: the sender may be in the
2193            // group and die before the call returns. A kill that then fails
2194            // only suppresses a deadlock report, which is the safe direction.
2195            // `kill(INT_MIN)` names no group; Linux refuses it with ESRCH.
2196            let group = tgid.checked_neg().map(DetPid::from_raw);
2197            if group.is_some() {
2198                crate::tool_global::notify_unresolved_sigkill(guest, group).await;
2199            }
2200            // Every member is retired at this turn
2201            // (https://github.com/rrnewton/hermit/issues/3994).
2202            if guest.config().sequentialize_threads
2203                && let Some(group) = group
2204                && let Some(reservation) = reserve_sigkill_group(guest, group).await
2205            {
2206                return self.send_reserved_sigkill(guest, reservation, call).await;
2207            }
2208            return Ok(self.record_or_replay(guest, call).await?);
2209        }
2210        if tgid <= 0 {
2211            return self.refuse_group_signal(guest, tgid, call.sig()).await;
2212        }
2213        // A kill may name the process by any of its live threads' ids (Linux's
2214        // kill_pid_info looks the id up as a task); everything below that acts
2215        // on the process uses its leader
2216        // (https://github.com/rrnewton/hermit/issues/4094).
2217        let process = signal_target_process(guest, DetPid::from_raw(tgid))
2218            .await
2219            .map_or(tgid, |process| process.as_raw());
2220        // Exact self-SIGKILL is group-fatal, so it has no recipient-selection
2221        // ambiguity even when the process has several live threads. Reserve it
2222        // before the generic process-signal path rejects that thread set.
2223        if self
2224            .reserve_controlled_self_sigkill_exit(
2225                guest,
2226                call.sig(),
2227                Some(DetPid::from_raw(process)),
2228                None,
2229            )
2230            .await
2231        {
2232            return Ok(self.record_or_replay(guest, call).await?);
2233        }
2234        // A SIGKILL to another process retires every thread of it at this
2235        // turn (https://github.com/rrnewton/hermit/issues/3994). It needs no
2236        // recipient, so a multithreaded target is accepted.
2237        if call.sig() == libc::SIGKILL
2238            && let Some(reservation) = reserve_sigkill(guest, DetTid::from_raw(tgid)).await
2239        {
2240            return self.send_reserved_sigkill(guest, reservation, call).await;
2241        }
2242        match self
2243            .own_process_signal(guest, Sysno::kill, tgid, process, call.sig())
2244            .await?
2245        {
2246            OwnProcessSend::Admitted => {
2247                return self
2248                    .forward_own_process_signal(guest, call.sig(), call, DetTid::from_raw(tgid))
2249                    .await;
2250            }
2251            OwnProcessSend::Refused(answer) => return answer,
2252            OwnProcessSend::NotOwn => {}
2253        }
2254        let Some(tid) = self
2255            .process_signal_target(guest, Sysno::kill, DetPid::from_raw(process), call.sig())
2256            .await?
2257        else {
2258            // A zombie: exited, and its parent can still wait for it. Linux's
2259            // kill_pid_info still finds it and the send succeeds, discarding
2260            // the signal, so answer 0 without a system call: the host process
2261            // may already be gone if a backend reaped it, and the logical
2262            // answer must not depend on when
2263            // (https://github.com/rrnewton/hermit/issues/4091). Linux checks
2264            // the signal number after finding the task, so an invalid one is
2265            // EINVAL.
2266            if !(1..=libc::SIGRTMAX()).contains(&call.sig()) {
2267                return Err(Errno::EINVAL.into());
2268            }
2269            return Ok(0);
2270        };
2271        let value = if !guest
2272            .config()
2273            .backend
2274            .requires_thread_directed_process_signals
2275        {
2276            self.send_guest_signal(
2277                guest,
2278                call,
2279                tid,
2280                call.sig(),
2281                Some(DetPid::from_raw(process)),
2282                false,
2283                DetTid::from_raw(tgid),
2284            )
2285            .await?
2286        } else if process == self.detpid.as_raw()
2287            && tid == guest.thread_state().dettid
2288            && (1..=libc::SIGRTMAX()).contains(&call.sig())
2289        {
2290            // This backend must name the receiving thread, but an original
2291            // process-directed kill still carries SI_USER, not tgkill's
2292            // SI_TKILL. For the current task Linux accepts an explicit SI_USER
2293            // payload. Keep the sender in the same deterministic PID namespace
2294            // as getpid; obtain its real UID from this actual task, not a host
2295            // lookup using the deterministic PID. Other tasks cannot accept
2296            // caller-supplied SI_USER and retain the existing tgkill route.
2297            let uid = guest.inject_with_retry(syscalls::Getuid::new()).await? as u32;
2298            let mut info = [0_u8; 128];
2299            info[0..4].copy_from_slice(&call.sig().to_ne_bytes());
2300            info[8..12].copy_from_slice(&libc::SI_USER.to_ne_bytes());
2301            // Linux x86-64 siginfo's sender union follows three ints and
2302            // alignment padding: pid_t at 16, uid_t at 20.
2303            info[16..20].copy_from_slice(&self.detpid.as_raw().to_ne_bytes());
2304            info[20..24].copy_from_slice(&uid.to_ne_bytes());
2305            let mut stack = guest.stack().await;
2306            let info = stack.push(info);
2307            let _stack_guard = stack.commit()?;
2308            let targeted = syscalls::RtTgsigqueueinfo::new()
2309                .with_tgid(process)
2310                .with_tid(tid.as_raw())
2311                .with_sig(call.sig())
2312                // The syscall wrapper uses AddrMut, but Linux only reads this
2313                // private siginfo. Its committed storage outlives the send.
2314                .with_siginfo(Some(unsafe { info.cast().into_mut() }));
2315            // A process-directed kill: Linux classifies the send against
2316            // the leader (https://github.com/rrnewton/hermit/issues/4293).
2317            self.send_guest_signal(
2318                guest,
2319                targeted,
2320                tid,
2321                call.sig(),
2322                Some(DetPid::from_raw(process)),
2323                false,
2324                DetTid::from_raw(tgid),
2325            )
2326            .await?
2327        } else {
2328            let targeted = syscalls::Tgkill::new()
2329                .with_tgid(process)
2330                .with_tid(tid.as_raw())
2331                .with_sig(call.sig());
2332            self.send_guest_signal(
2333                guest,
2334                targeted,
2335                tid,
2336                call.sig(),
2337                Some(DetPid::from_raw(process)),
2338                false,
2339                DetTid::from_raw(tgid),
2340            )
2341            .await?
2342        };
2343        self.notify_cross_task_signal(
2344            guest,
2345            tid,
2346            call.sig(),
2347            Some(DetPid::from_raw(process)),
2348            crate::tool_global::SignalScope::Process,
2349        )
2350        .await;
2351        Ok(value)
2352    }
2353
2354    // AUTONOMOUS-BOT-IMPLEMENTED
2355    // TODO-HUMAN-REVIEW(https://github.com/rrnewton/hermit/issues/4046)
2356    /// Refuse by name a `kill` to a process group (`pid` 0 for the caller's own,
2357    /// `-pgid` for another) or to every process it may signal (`pid` -1).
2358    ///
2359    /// Linux sends the signal to each process in the set
2360    /// (`__kill_pgrp_info`, `kill_something_info` in kernel/signal.c), and each
2361    /// process then picks its receiving thread as a process-directed signal
2362    /// does. Detcore models neither the set's membership nor that choice, so
2363    /// the call goes through the unsupported-operation policy: a fail-closed
2364    /// run stops with the policy-refusal status and
2365    /// `--allow-unsupported-syscalls` returns ENOSYS, as the call did before.
2366    /// A SIGKILL to another group is forwarded before this point
2367    /// (`can_forward_process_group_signal`) when threads are sequentialized,
2368    /// except on a backend that needs thread-directed process signals (DBT),
2369    /// where it is refused here too. Without sequentialization every such kill
2370    /// is refused here, for host safety: the guest's process group is
2371    /// inherited from Hermit's (https://github.com/rrnewton/hermit/issues/4057).
2372    async fn refuse_group_signal<G: Guest<Self>>(
2373        &self,
2374        guest: &mut G,
2375        pid: libc::pid_t,
2376        sig: libc::c_int,
2377    ) -> Result<i64, Error> {
2378        let target = match pid {
2379            0 => "its own process group".to_owned(),
2380            -1 => "every process it may signal".to_owned(),
2381            pid => format!("process group {}", pid.unsigned_abs()),
2382        };
2383        let reason = if guest.config().sequentialize_threads {
2384            "Detcore does not model process-group membership or each process's receiving \
2385             thread (https://github.com/rrnewton/hermit/issues/4046)"
2386        } else {
2387            "with threads not sequentialized (--no-sequentialize-threads, --strace-only) it \
2388             would go to the host kernel as is, and the guest's process group is inherited from \
2389             Hermit's, so it can reach Hermit and the processes that started it \
2390             (https://github.com/rrnewton/hermit/issues/4057)"
2391        };
2392        tracing::error!(
2393            "[detcore, dtid {}] signal {} to {} by kill is not supported: {}",
2394            guest.thread_state().dettid,
2395            sig,
2396            target,
2397            reason,
2398        );
2399        self.refuse_unserviceable_operation(guest, Sysno::kill, Errno::ENOSYS)
2400            .await
2401    }
2402
2403    /// Decide a process-directed `sig` that the calling thread sends by `sysno`
2404    /// to `pid` when `pid` names its own process (`process`, the process that
2405    /// `pid` names: any of its live threads' ids names it), and the process
2406    /// has another live thread (https://github.com/rrnewton/hermit/issues/4034).
2407    /// Only where the kernel's signal state for a guest thread is the guest's
2408    /// own (the legacy bundled condition
2409    /// `bundled_signal_facts::kernel_signal_state_is_guests`: ptrace and
2410    /// e9patch): the decision reads each thread's blocked, pending, ignored
2411    /// and caught sets from the kernel, and Detcore reads every other input
2412    /// from the schedule.
2413    async fn own_process_signal<G: Guest<Self>>(
2414        &self,
2415        guest: &mut G,
2416        sysno: Sysno,
2417        pid: libc::pid_t,
2418        process: libc::pid_t,
2419        sig: libc::c_int,
2420    ) -> Result<OwnProcessSend, Error> {
2421        if !bundled_signal_facts::kernel_signal_state_is_guests(&guest.config().backend) {
2422            return Ok(OwnProcessSend::NotOwn);
2423        }
2424        let sender = guest.thread_state().dettid;
2425        if process != self.detpid.as_raw() {
2426            return Ok(OwnProcessSend::NotOwn);
2427        }
2428        // Linux prefers the thread `pid` names when it takes the signal; a
2429        // sibling's id, like the process's, leaves the sender as the receiver
2430        // only when every sibling blocks it.
2431        let names_sender = pid == sender.as_raw();
2432        let inputs = own_process_signal_inputs(guest).await;
2433        if inputs
2434            .siblings
2435            .iter()
2436            .all(|(_, state)| *state == SiblingSignalState::ExitGranted)
2437        {
2438            return Ok(OwnProcessSend::NotOwn);
2439        }
2440        let state = read_thread_wait_signal_state(guest.pid(), guest.tid())?;
2441        let send = OwnProcessSignal {
2442            sig,
2443            names_sender,
2444            blocked: state.blocked,
2445            thread_pending: state.thread_pending,
2446            ignored: state.ignored,
2447            caught: state.caught,
2448            inputs,
2449            record_replay: self.cfg.recordreplay_modes,
2450            schedule_replay: self.cfg.replay_schedule_from.is_some(),
2451            stacktrace_signal: self.cfg.stacktrace_signal.is_some(),
2452            posthook_anchor: !guest.thread_state().stats.hb_pending_posthook.is_empty(),
2453            signalfd: guest.thread_state().holds_a_signalfd(),
2454        };
2455        tracing::debug!(
2456            "[detcore, dtid {}] signal {} to its own process: {:?}",
2457            sender,
2458            sig,
2459            send
2460        );
2461        let Some(refusal) = own_process_signal_refusal(&send) else {
2462            return Ok(OwnProcessSend::Admitted);
2463        };
2464        tracing::error!(
2465            "[detcore, dtid {}] process-directed signal {} to process {} by {} is not supported: \
2466             {} (https://github.com/rrnewton/hermit/issues/4034)",
2467            sender,
2468            sig,
2469            self.detpid,
2470            sysno,
2471            refusal,
2472        );
2473        Ok(OwnProcessSend::Refused(
2474            self.refuse_unserviceable_operation(guest, sysno, Errno::ENOSYS)
2475                .await,
2476        ))
2477    }
2478
2479    /// Forward an admitted process-directed signal to the sender's own process
2480    /// unchanged, holding the sender's turn until it takes the signal
2481    /// (`own_signal_turn_hold`). A call the kernel fails sends nothing and
2482    /// holds nothing.
2483    async fn forward_own_process_signal<G: Guest<Self>, C>(
2484        &self,
2485        guest: &mut G,
2486        sig: libc::c_int,
2487        call: C,
2488        named: DetTid,
2489    ) -> Result<i64, Error>
2490    where
2491        C: Into<syscalls::Syscall>,
2492        syscalls::Syscall: From<C>,
2493    {
2494        let token = self
2495            .discard_pre_send(guest, named, QueueId::Process(self.detpid), sig)
2496            .await;
2497        let call: syscalls::Syscall = call.into();
2498        let siginfo = sent_siginfo(guest, &call, sig);
2499        guest.thread_state_mut().own_signal_turn_hold = Some(sig);
2500        let result = self.record_or_replay(guest, call).await;
2501        if result.is_err() {
2502            guest.thread_state_mut().own_signal_turn_hold = None;
2503        } else {
2504            self.discard_sent(guest, token, siginfo).await;
2505        }
2506        Ok(result?)
2507    }
2508
2509    /// Forward a signal to a task of the caller's own PID namespace's init
2510    /// that the kernel drops (`own_namespace_init_drops`), recording, around
2511    /// the send, the copy that ptrace still queues (`discard_pre_send`).
2512    async fn send_to_own_init<G: Guest<Self>, C>(
2513        &self,
2514        guest: &mut G,
2515        call: C,
2516        named: DetTid,
2517        queue: QueueId,
2518        sig: libc::c_int,
2519    ) -> Result<i64, Error>
2520    where
2521        C: Into<syscalls::Syscall>,
2522        syscalls::Syscall: From<C>,
2523    {
2524        let token = self.discard_pre_send(guest, named, queue, sig).await;
2525        let call: syscalls::Syscall = call.into();
2526        let siginfo = sent_siginfo(guest, &call, sig);
2527        let result = self.record_or_replay(guest, call).await;
2528        if result.is_ok() {
2529            self.discard_sent(guest, token, siginfo).await;
2530        }
2531        Ok(result?)
2532    }
2533
2534    /// Classify, in the sender's turn and before the physical send, a guest's
2535    /// send of `raw_signal` into `queue` naming `named`, and read the queue
2536    /// (`scheduler::discarded_at_send`, <https://github.com/rrnewton/hermit/issues/4293>).
2537    /// `None` where Detcore does not sequentialize threads, or for a signal
2538    /// the record does not track.
2539    pub(crate) async fn discard_pre_send<G: Guest<Self>>(
2540        &self,
2541        guest: &mut G,
2542        named: DetTid,
2543        queue: QueueId,
2544        raw_signal: i32,
2545    ) -> Option<DiscardToken> {
2546        if !crate::scheduler::discarded_at_send::records(guest.config())
2547            || !(1..32).contains(&raw_signal)
2548        {
2549            return None;
2550        }
2551        match crate::tool_global::discarded_signal(
2552            guest,
2553            DiscardedSignalControl::PreSend {
2554                named,
2555                queue,
2556                signal: raw_signal,
2557            },
2558        )
2559        .await
2560        {
2561            DiscardedSignalAnswer::Token(token) => Some(token),
2562            _ => None,
2563        }
2564    }
2565
2566    /// Record a send `token` classified (`discard_pre_send`) once the send
2567    /// succeeded, with the siginfo the receiver sees (`sent_siginfo`).
2568    pub(crate) async fn discard_sent<G: Guest<Self>>(
2569        &self,
2570        guest: &mut G,
2571        token: Option<DiscardToken>,
2572        siginfo: Option<KernelSiginfo>,
2573    ) {
2574        if let Some(token) = token {
2575            crate::tool_global::discarded_signal(
2576                guest,
2577                DiscardedSignalControl::Sent(token, siginfo),
2578            )
2579            .await;
2580        }
2581    }
2582
2583    /// What an `rt_sigqueueinfo` whose `siginfo_t` Hermit may not be able to
2584    /// read comes to, decided before admission (`do_rt_sigqueueinfo` in
2585    /// kernel/signal.c). No call that Linux could deliver reaches the kernel
2586    /// without admission (Codex re-check 2 of
2587    /// https://github.com/rrnewton/hermit/pull/4116).
2588    ///
2589    /// The kernel always copies the first 48 bytes (`kernel_siginfo_t`) and
2590    /// the other 80 only for a `si_code` whose layout it does not know
2591    /// (`copy_siginfo_from_user`). Its `copy_from_user` reads what user mode
2592    /// can: on x86 a page with any of read, write or execute permission; it
2593    /// faults on a `PROT_NONE` page; and a fault in a hole just below a
2594    /// grow-down mapping can grow that mapping and succeed. The tracer's own
2595    /// reads say nothing about that (`process_vm_readv` refuses a write-only
2596    /// page, and `/proc/<tid>/mem` force-reads a `PROT_NONE` one), so the
2597    /// mappings of `/proc/<tid>/smaps` decide first:
2598    /// - the first byte of the 48 that user mode cannot read lies in a
2599    ///   `PROT_NONE` mapping, or in a hole whose next mapping above is not
2600    ///   grow-down (`VmFlags` `gd`; only that mapping can grow into it):
2601    ///   EFAULT is certain, and Hermit answers it without the kernel;
2602    /// - any other byte of the 128 that user mode cannot read (a hole below a
2603    ///   grow-down mapping, a tail running into a hole or a `PROT_NONE` page),
2604    ///   or a listing that cannot be read: `Unreadable`, refused by name;
2605    /// - all 128 user-readable: the tracer reads them (`process_vm_readv`, then
2606    ///   `/proc/<tid>/mem` for a write-only page), and a page neither reaches
2607    ///   (a `VM_IO`/`VM_PFNMAP` page such as the vDSO's `[vvar]`) is
2608    ///   `Unreadable`. A `si_code` only the target thread itself may use
2609    ///   (`si_code >= 0` or `SI_TKILL`, from a caller that is not `pid`) is
2610    ///   then `KernelFails`: after a complete copy Linux fails it with EPERM,
2611    ///   or E2BIG first, and sends nothing, so it goes to the kernel unchanged.
2612    fn rt_sigqueueinfo_precheck<G: Guest<Self>>(
2613        &self,
2614        guest: &mut G,
2615        call: &syscalls::RtSigqueueinfo,
2616    ) -> RtSigqueueinfoPrecheck {
2617        const SIZE: usize = std::mem::size_of::<libc::siginfo_t>();
2618        // `sizeof(kernel_siginfo_t)` on x86_64: the part every copy reads.
2619        const KERNEL_SIGINFO: usize = 48;
2620        let address = call.siginfo().map_or(0, |address| address.as_raw());
2621        let Ok(smaps) = std::fs::read_to_string(format!("/proc/{}/smaps", guest.tid().as_raw()))
2622        else {
2623            return RtSigqueueinfoPrecheck::Unreadable;
2624        };
2625        let mappings = parse_smaps(&smaps);
2626        match first_user_unreadable(&mappings, address, KERNEL_SIGINFO) {
2627            None => {}
2628            Some(Unreadable::NoPermission)
2629            | Some(Unreadable::Hole {
2630                below_growsdown: false,
2631            }) => {
2632                return RtSigqueueinfoPrecheck::Efault;
2633            }
2634            Some(Unreadable::Hole {
2635                below_growsdown: true,
2636            }) => {
2637                return RtSigqueueinfoPrecheck::Unreadable;
2638            }
2639        }
2640        if first_user_unreadable(&mappings, address, SIZE).is_some() {
2641            return RtSigqueueinfoPrecheck::Unreadable;
2642        }
2643        let read = call.siginfo().and_then(|info| {
2644            guest.memory().read_value(info).ok().or_else(|| {
2645                use std::os::unix::fs::FileExt;
2646                let mut bytes = [0u8; SIZE];
2647                std::fs::File::open(format!("/proc/{}/mem", guest.tid().as_raw()))
2648                    .and_then(|mem| mem.read_exact_at(&mut bytes, address as u64))
2649                    .ok()?;
2650                // SAFETY: `siginfo_t` is plain data, and `bytes` holds exactly
2651                // one, read from the guest.
2652                Some(unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast::<libc::siginfo_t>()) })
2653            })
2654        });
2655        let Some(info) = read else {
2656            return RtSigqueueinfoPrecheck::Unreadable;
2657        };
2658        let code = info.si_code;
2659        if (code >= 0 || code == libc::SI_TKILL)
2660            && guest.thread_state().dettid.as_raw() != call.tgid()
2661        {
2662            RtSigqueueinfoPrecheck::KernelFails
2663        } else {
2664            RtSigqueueinfoPrecheck::Proceeds
2665        }
2666    }
2667
2668    /// Record, in the sending call's turn and before it reaches the kernel, the
2669    /// signals a send of a default-stop signal lets Linux send to an orphaned
2670    /// process group later (`orphaned_group_signals`), for every process of
2671    /// the container, whatever the target and its disposition and whether the
2672    /// send then succeeds: no gated wait ends for them, and a process-directed
2673    /// send the sender does not block them for is refused
2674    /// (https://github.com/rrnewton/hermit/issues/4034). A send of SIGSTKFLT,
2675    /// Reverie's timer marker, is recorded too
2676    /// (`Scheduler::record_guest_marker_signal`).
2677    pub(crate) async fn record_orphaned_group_signals<G: Guest<Self>>(
2678        &self,
2679        guest: &mut G,
2680        sig: libc::c_int,
2681    ) {
2682        if sig == libc::SIGSTKFLT {
2683            crate::tool_global::record_guest_marker_signal(guest).await;
2684        }
2685        let signals = orphaned_group_signals(sig);
2686        if signals != 0
2687            && bundled_signal_facts::host_timed_signal_sources_are_physical(&guest.config().backend)
2688        {
2689            record_host_timed_signals(guest, HostTimedSignalScope::Container, signals).await;
2690        }
2691    }
2692
2693    /// Whether to drop, answering 0 and sending nothing, a signal `sig` the
2694    /// guest addresses to `target` (a pid, or a tid in thread group `tgid` for
2695    /// the calls that name one) that is one of Hermit's own tasks: its container
2696    /// init, PID 1 of the guest's PID namespace, or another thread of that
2697    /// process. A forwarded SIGTERM ended Hermit's run
2698    /// (https://github.com/rrnewton/hermit/issues/4066).
2699    ///
2700    /// This is what Linux does for a signal sent from inside a PID namespace to
2701    /// its init when the init has no handler for it: `sig_task_ignored` drops
2702    /// it (the init is `SIGNAL_UNKILLABLE`, and a sender in its own namespace
2703    /// does not force it), SIGKILL included, and the call returns 0. To the
2704    /// guest Hermit is such an init; the handlers Hermit installs are for
2705    /// supervisors outside the namespace. Signal 0, an invalid signal number
2706    /// and a nonpositive target go to the caller's own path, as do targets
2707    /// that are guest tasks ([`crate::tool_global::hermit_task_named`]).
2708    /// The task a positive pid the calling thread names refers to. At depth 0
2709    /// the pid is the DetTid. In a nested PID namespace it is a pid of that
2710    /// namespace, translated through the scheduler's record
2711    /// (`scheduler::pid_namespaces`, https://github.com/rrnewton/hermit/issues/4155);
2712    /// a pid no task of the namespace has is ESRCH, as Linux's `find_vpid`
2713    /// answers. Detcore's own bookkeeping uses the translated task; a call
2714    /// forwarded to the kernel keeps the guest's number, which the kernel reads
2715    /// in the caller's namespace. On a backend that rewrites a process signal
2716    /// into a thread-directed one with Detcore's ids, a nested caller is
2717    /// refused by name.
2718    async fn name_guest_pid<G: Guest<Self>>(
2719        &self,
2720        guest: &mut G,
2721        sysno: Sysno,
2722        pid: libc::pid_t,
2723    ) -> NamedGuestPid {
2724        if !guest.thread_state().nested_pid_namespace {
2725            return NamedGuestPid::Task {
2726                task: DetTid::from_raw(pid),
2727                own_init_caught: None,
2728            };
2729        }
2730        let refusal = if guest
2731            .config()
2732            .backend
2733            .requires_thread_directed_process_signals
2734        {
2735            "this backend sends process signals with Detcore's container-namespace ids".to_owned()
2736        } else {
2737            match crate::tool_global::guest_pid(guest, pid).await {
2738                GuestPidAnswer::Task {
2739                    task,
2740                    own_init_caught,
2741                } => {
2742                    return NamedGuestPid::Task {
2743                        task,
2744                        own_init_caught,
2745                    };
2746                }
2747                GuestPidAnswer::NoSuchPid => {
2748                    return NamedGuestPid::Answer(Err(Errno::ESRCH.into()));
2749                }
2750                GuestPidAnswer::Untranslatable(reason) => reason,
2751            }
2752        };
2753        tracing::error!(
2754            "[detcore, dtid {}] {} naming pid {} from a nested PID namespace is not supported: {} (https://github.com/rrnewton/hermit/issues/4155)",
2755            guest.thread_state().dettid,
2756            sysno,
2757            pid,
2758            refusal,
2759        );
2760        NamedGuestPid::Answer(
2761            self.refuse_unserviceable_operation(guest, sysno, Errno::ENOSYS)
2762                .await,
2763        )
2764    }
2765
2766    /// Whether the kernel drops `sig` sent to a task of the caller's own PID
2767    /// namespace's init (`own_init_caught`, `name_guest_pid`): Linux drops it
2768    /// unless the init has a handler for it, and SIGKILL and SIGSTOP always
2769    /// (`SIGNAL_UNKILLABLE`, `sig_task_ignored`). Such a call is forwarded
2770    /// unchanged: the kernel makes its own checks (signal number, siginfo),
2771    /// then drops the signal and answers 0, and nothing reaches a task, so
2772    /// Detcore has nothing to schedule or record.
2773    pub(crate) fn own_namespace_init_drops(own_init_caught: Option<u64>, sig: libc::c_int) -> bool {
2774        own_init_caught.is_some_and(|caught| {
2775            (1..=libc::SIGRTMAX()).contains(&sig)
2776                && (sig == libc::SIGKILL
2777                    || sig == libc::SIGSTOP
2778                    || caught & kernel_sigset_bit(sig) == 0)
2779        })
2780    }
2781
2782    async fn drop_signal_to_hermit<G: Guest<Self>>(
2783        &self,
2784        guest: &mut G,
2785        sysno: Sysno,
2786        tgid: Option<libc::pid_t>,
2787        target: libc::pid_t,
2788        sig: libc::c_int,
2789    ) -> bool {
2790        if !(1..=libc::SIGRTMAX()).contains(&sig) || target <= 0 {
2791            return false;
2792        }
2793        if !crate::tool_global::names_hermit_task(guest, tgid, target).await {
2794            return false;
2795        }
2796        tracing::info!(
2797            "[detcore, dtid {}] {} of signal {} to task {}, one of Hermit's own: dropped and \
2798             answered 0, as Linux drops a signal from inside a PID namespace to its init \
2799             (https://github.com/rrnewton/hermit/issues/4066)",
2800            guest.thread_state().dettid,
2801            sysno,
2802            sig,
2803            target,
2804        );
2805        true
2806    }
2807
2808    // AUTONOMOUS-BOT-IMPLEMENTED
2809    // TODO-HUMAN-REVIEW(https://github.com/rrnewton/hermit/issues/4034)
2810    /// The thread, of `tgid`'s live `targets`, that a process-directed signal
2811    /// `sig` is routed to.
2812    ///
2813    /// With several live threads the call is refused by name: Linux's
2814    /// `complete_signal` (kernel/signal.c) gives the signal to any thread that
2815    /// `wants_signal` (one that does not block it, is not exiting and is not
2816    /// stopped), which depends on the threads' masks and run states, and Detcore
2817    /// does not model that choice. The refusal goes through the
2818    /// unsupported-operation policy, so a fail-closed run stops with the
2819    /// policy-refusal status and `--allow-unsupported-syscalls` returns ENOSYS.
2820    pub(crate) async fn process_signal_target<G: Guest<Self>>(
2821        &self,
2822        guest: &mut G,
2823        sysno: Sysno,
2824        tgid: DetPid,
2825        sig: libc::c_int,
2826    ) -> Result<Option<DetTid>, Error> {
2827        let (targets, zombie) = resolve_kill_targets_and_exit(guest, tgid).await;
2828        // SIGKILL ends the whole thread group whichever thread receives it, so
2829        // it needs no recipient choice. On a backend that sends process
2830        // signals to a named thread (DBT), whose kill notice retires the
2831        // target's whole group (`Scheduler::note_process_sigkill`), send it to
2832        // the lowest live thread (https://github.com/rrnewton/hermit/issues/4362).
2833        // Elsewhere a SIGKILL to another process is reserved and retired
2834        // before this point.
2835        if sig == libc::SIGKILL
2836            && targets.len() > 1
2837            && guest
2838                .config()
2839                .backend
2840                .requires_thread_directed_process_signals
2841        {
2842            return Ok(targets.first().copied());
2843        }
2844        match deterministic_kill_target(&targets, zombie, sig) {
2845            Err(Errno::ENOSYS) => {
2846                tracing::error!(
2847                    "[detcore, dtid {}] process-directed signal {} to process {} by {} is not supported: \
2848                     the process has {} live threads, and Detcore does not choose the receiving \
2849                     thread as Linux's complete_signal does \
2850                     (https://github.com/rrnewton/hermit/issues/4034)",
2851                    guest.thread_state().dettid,
2852                    sig,
2853                    tgid,
2854                    sysno,
2855                    targets.len(),
2856                );
2857                self.refuse_unserviceable_operation(guest, sysno, Errno::ENOSYS)
2858                    .await
2859                    .and(Err(Errno::ENOSYS.into()))
2860            }
2861            target => Ok(target?),
2862        }
2863    }
2864
2865    // AUTONOMOUS-BOT-IMPLEMENTED
2866    // TODO-HUMAN-REVIEW(#663)
2867    /// Send a thread-directed signal through the kernel. Guest PID/TID values are
2868    /// stable in the fresh PID namespace and delivery is scheduler-serialized.
2869    pub async fn handle_tgkill<G: Guest<Self>>(
2870        &self,
2871        guest: &mut G,
2872        call: syscalls::Tgkill,
2873    ) -> Result<i64, Error> {
2874        self.record_orphaned_group_signals(guest, call.sig()).await;
2875        // A nested caller names its own namespace's ids; Detcore's model uses
2876        // the tasks they name, and the forwarded call keeps them
2877        // (https://github.com/rrnewton/hermit/issues/4155). Non-positive ids
2878        // are EINVAL in Linux before any lookup.
2879        let nested = guest.thread_state().nested_pid_namespace;
2880        let (tgid, tid) = if nested && call.tgid() > 0 && call.tid() > 0 {
2881            let (tid, own_init_caught) =
2882                match self.name_guest_pid(guest, Sysno::tgkill, call.tid()).await {
2883                    NamedGuestPid::Task {
2884                        task,
2885                        own_init_caught,
2886                    } => (task, own_init_caught),
2887                    NamedGuestPid::Answer(answer) => return answer,
2888                };
2889            let tgid = match self.name_guest_pid(guest, Sysno::tgkill, call.tgid()).await {
2890                NamedGuestPid::Task { task, .. } => task,
2891                NamedGuestPid::Answer(answer) => return answer,
2892            };
2893            if Self::own_namespace_init_drops(own_init_caught, call.sig()) {
2894                return self
2895                    .send_to_own_init(guest, call, tid, QueueId::Thread(tid), call.sig())
2896                    .await;
2897            }
2898            (tgid.as_raw(), tid.as_raw())
2899        } else {
2900            (call.tgid(), call.tid())
2901        };
2902        if call.sig() == libc::SIGALRM {
2903            refuse_sigalrm(guest, SigalrmControl::SendTo(DetTid::from_raw(tid))).await?;
2904        }
2905        if !nested
2906            && self
2907                .drop_signal_to_hermit(guest, Sysno::tgkill, Some(tgid), tid, call.sig())
2908                .await
2909        {
2910            return Ok(0);
2911        }
2912        let _reserved = self
2913            .reserve_controlled_self_sigkill_exit(
2914                guest,
2915                call.sig(),
2916                Some(DetPid::from_raw(tgid)),
2917                Some(DetTid::from_raw(tid)),
2918            )
2919            .await;
2920        // A SIGKILL to a thread of another process ends that whole process,
2921        // and is retired at this turn, like `kill`'s. Only a valid pair is
2922        // reserved: Linux rejects a thread outside the named group (ESRCH) or a
2923        // non-positive id (EINVAL) before anything happens, so such a send
2924        // takes the ordinary path and gets the kernel's errno. Nor is a send
2925        // to a leader that has exited while its siblings run on
2926        // (`sigkill_names_an_exited_leader`).
2927        let mut exited_leader = false;
2928        if call.sig() == libc::SIGKILL
2929            && guest.config().sequentialize_threads
2930            && tgid > 0
2931            && tid > 0
2932            && registered_process_of(guest, DetTid::from_raw(tid)).await
2933                == Some(DetPid::from_raw(tgid))
2934        {
2935            exited_leader = sigkill_names_an_exited_leader(guest, DetTid::from_raw(tid)).await;
2936            if !exited_leader
2937                && let Some(reservation) = reserve_sigkill(guest, DetTid::from_raw(tid)).await
2938            {
2939                return self.send_reserved_sigkill(guest, reservation, call).await;
2940            }
2941        }
2942        let value = self
2943            .send_guest_signal(
2944                guest,
2945                call,
2946                DetTid::from_raw(call.tid()),
2947                call.sig(),
2948                None,
2949                true,
2950                DetTid::from_raw(tid),
2951            )
2952            .await?;
2953        // The kernel accepted a SIGKILL that changes nothing: no thread takes
2954        // it and no process dies, so the scheduler is not told of a kill.
2955        if exited_leader {
2956            return Ok(value);
2957        }
2958        // `pthread_kill` lowers to `tgkill`, so this is the ordinary way one
2959        // guest THREAD signals a sibling. Like `kill`, a successful cross-task
2960        // send must tell the scheduler, or a target parked in a child wait is
2961        // never woken and the wait hangs.
2962        self.notify_cross_task_signal(
2963            guest,
2964            DetTid::from_raw(tid),
2965            call.sig(),
2966            None,
2967            crate::tool_global::SignalScope::Thread,
2968        )
2969        .await;
2970        Ok(value)
2971    }
2972
2973    // AUTONOMOUS-BOT-IMPLEMENTED
2974    // TODO-HUMAN-REVIEW(#812)
2975    /// Send a thread-directed signal through the older two-argument `tkill`.
2976    /// Like its `tgkill` sibling, the target thread is addressed by a guest TID
2977    /// that is stable in the fresh PID namespace and delivery is
2978    /// scheduler-serialized, so forwarding the kernel call is deterministic.
2979    pub async fn handle_tkill<G: Guest<Self>>(
2980        &self,
2981        guest: &mut G,
2982        call: syscalls::Tkill,
2983    ) -> Result<i64, Error> {
2984        self.record_orphaned_group_signals(guest, call.sig()).await;
2985        // A nested caller names its own namespace's tid
2986        // (https://github.com/rrnewton/hermit/issues/4155).
2987        let nested = guest.thread_state().nested_pid_namespace;
2988        let tid = if nested && call.tid() > 0 {
2989            match self.name_guest_pid(guest, Sysno::tkill, call.tid()).await {
2990                NamedGuestPid::Task {
2991                    task,
2992                    own_init_caught,
2993                } => {
2994                    if Self::own_namespace_init_drops(own_init_caught, call.sig()) {
2995                        return self
2996                            .send_to_own_init(guest, call, task, QueueId::Thread(task), call.sig())
2997                            .await;
2998                    }
2999                    task.as_raw()
3000                }
3001                NamedGuestPid::Answer(answer) => return answer,
3002            }
3003        } else {
3004            call.tid()
3005        };
3006        if call.sig() == libc::SIGALRM {
3007            refuse_sigalrm(guest, SigalrmControl::SendTo(DetTid::from_raw(tid))).await?;
3008        }
3009        if !nested
3010            && self
3011                .drop_signal_to_hermit(guest, Sysno::tkill, None, tid, call.sig())
3012                .await
3013        {
3014            return Ok(0);
3015        }
3016        let _reserved = self
3017            .reserve_controlled_self_sigkill_exit(
3018                guest,
3019                call.sig(),
3020                None,
3021                Some(DetTid::from_raw(tid)),
3022            )
3023            .await;
3024        // A non-positive tid is EINVAL in Linux, before anything happens.
3025        let mut exited_leader = false;
3026        if call.sig() == libc::SIGKILL && guest.config().sequentialize_threads && tid > 0 {
3027            exited_leader = sigkill_names_an_exited_leader(guest, DetTid::from_raw(tid)).await;
3028            if !exited_leader
3029                && let Some(reservation) = reserve_sigkill(guest, DetTid::from_raw(tid)).await
3030            {
3031                return self.send_reserved_sigkill(guest, reservation, call).await;
3032            }
3033        }
3034        let value = self
3035            .send_guest_signal(
3036                guest,
3037                call,
3038                DetTid::from_raw(call.tid()),
3039                call.sig(),
3040                None,
3041                true,
3042                DetTid::from_raw(tid),
3043            )
3044            .await?;
3045        // As in `tgkill`, a SIGKILL to an exited leader changes nothing.
3046        if exited_leader {
3047            return Ok(value);
3048        }
3049        // Same wakeup obligation as `tgkill`; `tkill` is the older two-argument
3050        // spelling of the same thread-directed send.
3051        self.notify_cross_task_signal(
3052            guest,
3053            DetTid::from_raw(tid),
3054            call.sig(),
3055            None,
3056            crate::tool_global::SignalScope::Thread,
3057        )
3058        .await;
3059        Ok(value)
3060    }
3061
3062    /// Complete a reserved SIGKILL (https://github.com/rrnewton/hermit/issues/3994).
3063    ///
3064    /// A send whose victims exclude the caller's own process returns: it is
3065    /// sent, and then committed with its real result. One that includes the
3066    /// caller's process cannot return, because the kernel ends the caller:
3067    /// the caller records its own exit status for its parent (`CLD_KILLED`,
3068    /// `SIGKILL`), takes the `exit_group` grant for its own process, as
3069    /// `exit_group` does, commits the other victims inside that exit turn, and
3070    /// then sends. The commit comes after the grant: it installs the physical
3071    /// fence, which waits for victims that only the send itself kills. The
3072    /// reservation validated the target against the scheduler's record, so the
3073    /// send cannot fail in a way the caller sees.
3074    pub(crate) async fn send_reserved_sigkill<G: Guest<Self>>(
3075        &self,
3076        guest: &mut G,
3077        reservation: crate::scheduler::sigkill_retirement::SigkillReservation,
3078        call: impl Into<syscalls::Syscall> + Copy,
3079    ) -> Result<i64, Error> {
3080        if !reservation.includes_sender {
3081            let result = self.record_or_replay(guest, call).await;
3082            commit_sigkill(guest, reservation.token, result.is_ok()).await;
3083            return Ok(result?);
3084        }
3085        if self.cfg.backend.reports_kernel_child_exit_signals {
3086            let uid = crate::syscalls::real_uid(guest.tid().as_raw())
3087                .unwrap_or_else(|| unsafe { libc::getuid() });
3088            crate::tool_global::child_exit_sigchld(
3089                guest,
3090                crate::scheduler::child_exit_sigchld::ChildExitSigchldControl::ExitStatus {
3091                    code: libc::CLD_KILLED,
3092                    status: libc::SIGKILL,
3093                    uid,
3094                },
3095            )
3096            .await;
3097        }
3098        let request = guest.thread_state().mk_request(
3099            ResourceID::Exit {
3100                group: true,
3101                process: guest.thread_state().detpid.expect("detpid unset"),
3102                mm: guest.thread_state().mm_id,
3103            },
3104            Permission::RW,
3105        );
3106        resource_request(guest, request).await;
3107        commit_sigkill(guest, reservation.token, true).await;
3108        Ok(self.record_or_replay(guest, call).await?)
3109    }
3110
3111    /// Send a guest's signal with `syscall`, first recording, for a `SIGCHLD`,
3112    /// the queue its copy will join (`record_guest_sigchld_send`), and undoing
3113    /// that record if the send fails. Recorded before the physical send: a
3114    /// thread outside the schedule (in a real `rt_sigsuspend` or blocking
3115    /// call) can take the copy the moment it is queued, before this handler
3116    /// could record it afterwards (the Claude re-check of
3117    /// https://github.com/rrnewton/hermit/pull/4131). `thread_directed`: the
3118    /// send names one thread (`tkill`, `tgkill`, `rt_tgsigqueueinfo`, a
3119    /// thread-scoped `pidfd_send_signal`). `named`: the task Linux reads to
3120    /// decide whether it discards the signal (`kill`'s pid, `tgkill`'s tid),
3121    /// which the discarded-at-send record classifies the send against
3122    /// (`discard_pre_send`).
3123    #[expect(
3124        clippy::too_many_arguments,
3125        reason = "each argument is one fact about the send the kernel call cannot tell"
3126    )]
3127    pub(crate) async fn send_guest_signal<G, S>(
3128        &self,
3129        guest: &mut G,
3130        syscall: S,
3131        target: DetTid,
3132        raw_signal: i32,
3133        target_process: Option<DetPid>,
3134        thread_directed: bool,
3135        named: DetTid,
3136    ) -> Result<i64, Error>
3137    where
3138        G: Guest<Self>,
3139        S: Into<reverie::syscalls::Syscall>,
3140    {
3141        use crate::scheduler::child_exit_sigchld::ChildExitSigchldAnswer;
3142        use crate::scheduler::child_exit_sigchld::ChildExitSigchldControl;
3143        let mut undo = None;
3144        if raw_signal == libc::SIGCHLD && guest.config().sequentialize_threads {
3145            // Without a process, or on a backend that sends process signals to
3146            // a thread, the copy joins the target's private queue.
3147            if thread_directed
3148                || target_process.is_none()
3149                || guest
3150                    .config()
3151                    .backend
3152                    .requires_thread_directed_process_signals
3153            {
3154                let answer = crate::tool_global::child_exit_sigchld(
3155                    guest,
3156                    ChildExitSigchldControl::PrivateSent { target },
3157                )
3158                .await;
3159                // A copy already pending there coalesces: only a new record is
3160                // undone.
3161                if answer == ChildExitSigchldAnswer::Placed(true) {
3162                    undo = Some(ChildExitSigchldControl::SendFailed {
3163                        private: Some(target),
3164                        shared: None,
3165                    });
3166                }
3167            } else if let Some(process) = target_process {
3168                crate::tool_global::child_exit_sigchld(
3169                    guest,
3170                    ChildExitSigchldControl::SharedSent { target: process },
3171                )
3172                .await;
3173                undo = Some(ChildExitSigchldControl::SendFailed {
3174                    private: None,
3175                    shared: Some(process),
3176                });
3177            }
3178        }
3179        // Without a process, or on a backend that sends process signals to a
3180        // thread, the copy joins the target's private queue.
3181        let queue = match target_process {
3182            Some(process)
3183                if !thread_directed
3184                    && !guest
3185                        .config()
3186                        .backend
3187                        .requires_thread_directed_process_signals =>
3188            {
3189                QueueId::Process(process)
3190            }
3191            _ => QueueId::Thread(target),
3192        };
3193        let token = self.discard_pre_send(guest, named, queue, raw_signal).await;
3194        let syscall: syscalls::Syscall = syscall.into();
3195        let siginfo = sent_siginfo(guest, &syscall, raw_signal);
3196        let result = self.record_or_replay(guest, syscall).await;
3197        if result.is_err()
3198            && let Some(undo) = undo
3199        {
3200            crate::tool_global::child_exit_sigchld(guest, undo).await;
3201        }
3202        if result.is_ok() {
3203            self.discard_sent(guest, token, siginfo).await;
3204        }
3205        Ok(result?)
3206    }
3207
3208    /// Tell the scheduler that a successful thread-directed send left a signal
3209    /// physically pending for another task.
3210    ///
3211    /// Shared by `kill`, `tgkill` and `tkill` so the three cannot drift: a fix
3212    /// applied to one spelling of "signal another task" must apply to all of
3213    /// them, which is exactly the gap that let a `pthread_kill` from a sibling
3214    /// thread hang a `waitid` that a `kill` from a sibling process could
3215    /// interrupt. Self-directed signals are excluded: the sender is running, so
3216    /// it is not parked waiting to be woken.
3217    pub(crate) async fn notify_cross_task_signal<G: Guest<Self>>(
3218        &self,
3219        guest: &mut G,
3220        target: DetTid,
3221        raw_signal: i32,
3222        target_process: Option<DetPid>,
3223        scope: crate::tool_global::SignalScope,
3224    ) {
3225        // ⚠️ NO `Signal::try_from` GATE. It used to stand here, and because
3226        // `nix`'s `Signal` models only 1..=31 it rejected EVERY realtime signal:
3227        // measured in-tree, the gate admitted exactly 1..=31 and zero of the 31
3228        // realtime signals. The notification was skipped silently, so a target
3229        // parked on `ResourceID::WaitChild` was never woken and the wait hung.
3230        // `SigWrapper` now carries the raw number, so every deliverable signal
3231        // can be represented and none is dropped for being unnameable. Signal
3232        // zero is only an existence/permission probe and queues no signal.
3233        if should_notify_cross_task_signal(guest.thread_state().dettid, target, raw_signal) {
3234            notify_signal_pending(guest, target, SigWrapper(raw_signal), target_process, scope)
3235                .await;
3236        }
3237    }
3238
3239    /// Refuse by name a guest's `SIGCHLD` that carries the scheduler's own-copy
3240    /// mark (`SI_QUEUE` with `OWN_SIGCHLD_MARK`), which a receiver in a nested
3241    /// PID namespace would take for the scheduler's copy
3242    /// (<https://github.com/rrnewton/hermit/issues/4155>). `None` for any other
3243    /// call; an unreadable siginfo is left to the kernel's EFAULT.
3244    pub(crate) async fn refuse_forged_own_sigchld<G: Guest<Self>>(
3245        &self,
3246        guest: &mut G,
3247        sysno: Sysno,
3248        signal: i32,
3249        info: Option<AddrMut<'_, libc::siginfo_t>>,
3250    ) -> Option<Result<i64, Error>> {
3251        if signal != libc::SIGCHLD {
3252            return None;
3253        }
3254        let bytes = read_siginfo(guest, info?)?;
3255        let (code, _) = crate::scheduler::child_exit_sigchld::siginfo_code_and_pid(&bytes);
3256        let value = i32::from_ne_bytes(bytes[24..28].try_into().expect("four bytes"));
3257        if code != libc::SI_QUEUE || value != crate::scheduler::child_exit_sigchld::OWN_SIGCHLD_MARK
3258        {
3259            return None;
3260        }
3261        tracing::error!(
3262            "[detcore, dtid {}] {} sends a SIGCHLD carrying the scheduler's own-copy mark {:#x}, which a nested PID namespace's receiver could not tell from the scheduler's (https://github.com/rrnewton/hermit/issues/4155)",
3263            guest.thread_state().dettid,
3264            sysno,
3265            crate::scheduler::child_exit_sigchld::OWN_SIGCHLD_MARK,
3266        );
3267        Some(
3268            self.refuse_unserviceable_operation(guest, sysno, Errno::EPERM)
3269                .await,
3270        )
3271    }
3272
3273    // AUTONOMOUS-BOT-IMPLEMENTED
3274    // TODO-HUMAN-REVIEW(#812)
3275    /// Queue a thread-directed signal with an accompanying `siginfo_t`. Like
3276    /// `tgkill`, the target is a specific thread named by stable guest TGID/TID
3277    /// and delivery is scheduler-serialized; the guest-supplied siginfo is
3278    /// deterministic input, so forwarding the kernel call is deterministic.
3279    pub async fn handle_rt_tgsigqueueinfo<G: Guest<Self>>(
3280        &self,
3281        guest: &mut G,
3282        call: syscalls::RtTgsigqueueinfo,
3283    ) -> Result<i64, Error> {
3284        if let Some(refused) = self
3285            .refuse_forged_own_sigchld(guest, Sysno::rt_tgsigqueueinfo, call.sig(), call.siginfo())
3286            .await
3287        {
3288            return refused;
3289        }
3290        self.record_orphaned_group_signals(guest, call.sig()).await;
3291        // A nested caller names its own namespace's tid
3292        // (https://github.com/rrnewton/hermit/issues/4155); a tid no task of
3293        // that namespace has goes to the kernel, which checks the siginfo
3294        // first and then answers ESRCH.
3295        let nested = guest.thread_state().nested_pid_namespace;
3296        let tid = if nested && call.tgid() > 0 && call.tid() > 0 {
3297            match self
3298                .name_guest_pid(guest, Sysno::rt_tgsigqueueinfo, call.tid())
3299                .await
3300            {
3301                NamedGuestPid::Task {
3302                    task,
3303                    own_init_caught,
3304                } => {
3305                    if Self::own_namespace_init_drops(own_init_caught, call.sig()) {
3306                        return self
3307                            .send_to_own_init(guest, call, task, QueueId::Thread(task), call.sig())
3308                            .await;
3309                    }
3310                    task.as_raw()
3311                }
3312                NamedGuestPid::Answer(Err(Error::Errno(Errno::ESRCH))) => {
3313                    return Ok(self.record_or_replay(guest, call).await?);
3314                }
3315                NamedGuestPid::Answer(answer) => return answer,
3316            }
3317        } else {
3318            call.tid()
3319        };
3320        if call.sig() == libc::SIGALRM {
3321            refuse_sigalrm(guest, SigalrmControl::SendTo(DetTid::from_raw(tid))).await?;
3322        }
3323        if !nested
3324            && self
3325                .drop_signal_to_hermit(
3326                    guest,
3327                    Sysno::rt_tgsigqueueinfo,
3328                    Some(call.tgid()),
3329                    tid,
3330                    call.sig(),
3331                )
3332                .await
3333        {
3334            return Ok(0);
3335        }
3336        // A SIGKILL to an exited leader changes nothing, as in `tgkill`
3337        // (https://github.com/rrnewton/hermit/issues/4445).
3338        let exited_leader = call.sig() == libc::SIGKILL
3339            && guest.config().sequentialize_threads
3340            && tid > 0
3341            && sigkill_names_an_exited_leader(guest, DetTid::from_raw(tid)).await;
3342        // Any other SIGKILL to a thread of a valid pair in another process
3343        // ends that thread's whole process, and is reserved and retired at
3344        // this turn as `tgkill`'s is
3345        // (https://github.com/rrnewton/hermit/issues/3994); before, its victims
3346        // were retired at their host-timed deaths. A send the kernel then
3347        // refuses (EFAULT, EPERM, E2BIG: its siginfo checks are subtle)
3348        // releases the reservation, because `send_reserved_sigkill` commits a
3349        // send that excludes the sender with its outcome. A send to the
3350        // sender's own process is not reserved: it would take the sender's
3351        // Exit grant before the call runs, and so must know beforehand that
3352        // the kernel accepts the siginfo (Codex review); it keeps its
3353        // host-timed retirement. Nor is a nested caller's send, whose tgid
3354        // names its own namespace.
3355        if call.sig() == libc::SIGKILL
3356            && !nested
3357            && !exited_leader
3358            && guest.config().sequentialize_threads
3359            && call.tgid() > 0
3360            && tid > 0
3361            && guest
3362                .thread_state()
3363                .detpid
3364                .is_none_or(|own| own.as_raw() != call.tgid())
3365            && registered_process_of(guest, DetTid::from_raw(tid)).await
3366                == Some(DetPid::from_raw(call.tgid()))
3367            && let Some(reservation) = reserve_sigkill(guest, DetTid::from_raw(tid)).await
3368        {
3369            if reservation.includes_sender {
3370                // Only when the sender's own process was not known above: give
3371                // the reservation back and take the unreserved path.
3372                commit_sigkill(guest, reservation.token, false).await;
3373            } else {
3374                return self.send_reserved_sigkill(guest, reservation, call).await;
3375            }
3376        }
3377        let value = self
3378            .send_guest_signal(
3379                guest,
3380                call,
3381                DetTid::from_raw(call.tid()),
3382                call.sig(),
3383                None,
3384                true,
3385                DetTid::from_raw(tid),
3386            )
3387            .await?;
3388        if exited_leader {
3389            return Ok(value);
3390        }
3391        // Thread-directed like `tgkill`, so it carries the same wakeup
3392        // obligation. `sigqueue`/`pthread_sigqueue` reach a parked sibling
3393        // through here.
3394        self.notify_cross_task_signal(
3395            guest,
3396            DetTid::from_raw(tid),
3397            call.sig(),
3398            None,
3399            crate::tool_global::SignalScope::Thread,
3400        )
3401        .await;
3402        Ok(value)
3403    }
3404
3405    // AUTONOMOUS-BOT-IMPLEMENTED
3406    // TODO-HUMAN-REVIEW(#812)
3407    // TODO-HUMAN-REVIEW(PR-1058): Review queued process-signal preservation.
3408    /// Queue a process-directed signal with an accompanying `siginfo_t`. Mirrors `handle_kill`:
3409    /// preserve process-directed delivery when the backend accepts guest PIDs, otherwise route an
3410    /// unambiguous positive-PID target to its sole live thread via `rt_tgsigqueueinfo`. Ambiguous
3411    /// multithreaded process-directed delivery is refused until Detcore models eligible masks.
3412    pub async fn handle_rt_sigqueueinfo<G: Guest<Self>>(
3413        &self,
3414        guest: &mut G,
3415        call: syscalls::RtSigqueueinfo,
3416    ) -> Result<i64, Error> {
3417        if let Some(refused) = self
3418            .refuse_forged_own_sigchld(guest, Sysno::rt_sigqueueinfo, call.sig(), call.siginfo())
3419            .await
3420        {
3421            return refused;
3422        }
3423        self.record_orphaned_group_signals(guest, call.sig()).await;
3424        let nested = guest.thread_state().nested_pid_namespace;
3425        if !guest.config().sequentialize_threads {
3426            if !nested
3427                && self
3428                    .drop_signal_to_hermit(
3429                        guest,
3430                        Sysno::rt_sigqueueinfo,
3431                        None,
3432                        call.tgid(),
3433                        call.sig(),
3434                    )
3435                    .await
3436            {
3437                return Ok(0);
3438            }
3439            return Ok(self.record_or_replay(guest, call).await?);
3440        }
3441
3442        // A nested caller names its own namespace's pid
3443        // (https://github.com/rrnewton/hermit/issues/4155); a pid no task of
3444        // that namespace has goes to the kernel, which checks the siginfo
3445        // first and then answers ESRCH.
3446        let tgid = if nested && call.tgid() > 0 {
3447            match self
3448                .name_guest_pid(guest, Sysno::rt_sigqueueinfo, call.tgid())
3449                .await
3450            {
3451                NamedGuestPid::Task {
3452                    task,
3453                    own_init_caught,
3454                } => {
3455                    if Self::own_namespace_init_drops(own_init_caught, call.sig()) {
3456                        return self
3457                            .send_to_own_init(guest, call, task, QueueId::Process(task), call.sig())
3458                            .await;
3459                    }
3460                    task.as_raw()
3461                }
3462                NamedGuestPid::Answer(Err(Error::Errno(Errno::ESRCH))) => {
3463                    return Ok(self.record_or_replay(guest, call).await?);
3464                }
3465                NamedGuestPid::Answer(answer) => return answer,
3466            }
3467        } else {
3468            call.tgid()
3469        };
3470        if tgid <= 0 {
3471            // POSIX.1b has no process groups: Linux's `do_rt_sigqueueinfo` looks
3472            // the pid up with `find_vpid`, which finds no process for 0 or a
3473            // negative pid, so the call fails (EFAULT for an unreadable
3474            // `siginfo_t`, EPERM for a forged `si_code`, E2BIG for an unknown
3475            // `si_code` with nonzero expansion bytes, otherwise ESRCH) and
3476            // sends nothing. The kernel's own answer is therefore deterministic
3477            // (https://github.com/rrnewton/hermit/issues/4046).
3478            return Ok(self.record_or_replay(guest, call).await?);
3479        }
3480        if call.sig() == 0 {
3481            // An existence check answers from the same exit model as a signal
3482            // (https://github.com/rrnewton/hermit/issues/4124): a process
3483            // Detcore saw exit and that is gone is ESRCH after the siginfo
3484            // checks, whatever the host has reaped by now.
3485            let (targets, zombie) =
3486                resolve_kill_targets_and_exit(guest, DetPid::from_raw(tgid)).await;
3487            if targets.is_empty() && zombie == Some(false) {
3488                return Ok(self
3489                    .record_or_replay(guest, call.with_tgid(NO_SUCH_PID))
3490                    .await?);
3491            }
3492            return Ok(self.record_or_replay(guest, call).await?);
3493        }
3494        if call.sig() == libc::SIGALRM {
3495            refuse_sigalrm(guest, SigalrmControl::SendTo(DetTid::from_raw(tgid))).await?;
3496        }
3497        if self
3498            .drop_signal_to_hermit(guest, Sysno::rt_sigqueueinfo, None, tgid, call.sig())
3499            .await
3500        {
3501            return Ok(0);
3502        }
3503        // A call the kernel fails without sending, after a complete copy of
3504        // its `siginfo_t` (EPERM for a `si_code` only the target thread itself
3505        // may use), goes to it unchanged; a copy that certainly faults is
3506        // answered EFAULT here; and a `siginfo_t` Hermit cannot read whole is
3507        // refused by name (`rt_sigqueueinfo_precheck`).
3508        if bundled_signal_facts::host_task_reads_enabled(&guest.config().backend) {
3509            match self.rt_sigqueueinfo_precheck(guest, &call) {
3510                RtSigqueueinfoPrecheck::KernelFails => {
3511                    return Ok(self.record_or_replay(guest, call).await?);
3512                }
3513                RtSigqueueinfoPrecheck::Efault => return Err(Errno::EFAULT.into()),
3514                RtSigqueueinfoPrecheck::Unreadable => {
3515                    tracing::error!(
3516                        "[detcore, dtid {}] rt_sigqueueinfo with a siginfo_t at {:#x} is not \
3517                         supported: Hermit cannot read all 128 bytes of it to decide the call \
3518                         (https://github.com/rrnewton/hermit/issues/4034)",
3519                        guest.thread_state().dettid,
3520                        call.siginfo().map_or(0, |info| info.as_raw()),
3521                    );
3522                    return self
3523                        .refuse_unserviceable_operation(
3524                            guest,
3525                            Sysno::rt_sigqueueinfo,
3526                            Errno::ENOSYS,
3527                        )
3528                        .await;
3529                }
3530                RtSigqueueinfoPrecheck::Proceeds => {}
3531            }
3532        }
3533        // As for kill, a live non-leader thread's id names its process
3534        // (https://github.com/rrnewton/hermit/issues/4094).
3535        let process = signal_target_process(guest, DetPid::from_raw(tgid))
3536            .await
3537            .map_or(tgid, |process| process.as_raw());
3538        match self
3539            .own_process_signal(guest, Sysno::rt_sigqueueinfo, tgid, process, call.sig())
3540            .await?
3541        {
3542            OwnProcessSend::Admitted => {
3543                return self
3544                    .forward_own_process_signal(guest, call.sig(), call, DetTid::from_raw(tgid))
3545                    .await;
3546            }
3547            OwnProcessSend::Refused(answer) => return answer,
3548            OwnProcessSend::NotOwn => {}
3549        }
3550        let target = match self
3551            .process_signal_target(
3552                guest,
3553                Sysno::rt_sigqueueinfo,
3554                DetPid::from_raw(process),
3555                call.sig(),
3556            )
3557            .await
3558        {
3559            // Gone: Linux checks the siginfo before it looks the process up
3560            // (EFAULT, then E2BIG for an unknown code with padding, then EPERM
3561            // for a forged code), and only then answers ESRCH. Let the kernel
3562            // make those checks against a pid no task can have, so its answer
3563            // cannot depend on whether the host has reaped the real one yet
3564            // (https://github.com/rrnewton/hermit/issues/4124).
3565            Err(Error::Errno(Errno::ESRCH)) => {
3566                return Ok(self
3567                    .record_or_replay(guest, call.with_tgid(NO_SUCH_PID))
3568                    .await?);
3569            }
3570            target => target?,
3571        };
3572        let Some(tid) = target else {
3573            // A zombie: its parent can still wait for it, so Linux still
3574            // finds it. Unlike kill, the kernel checks the siginfo first
3575            // (EFAULT, EPERM for a forged si_code, E2BIG), so let it answer:
3576            // it validates, finds the zombie, and returns 0. A backend that
3577            // must name a receiving thread has none to name, and keeps ESRCH
3578            // (https://github.com/rrnewton/hermit/issues/4091).
3579            if guest
3580                .config()
3581                .backend
3582                .requires_thread_directed_process_signals
3583            {
3584                return Err(Errno::ESRCH.into());
3585            }
3586            return Ok(self.record_or_replay(guest, call).await?);
3587        };
3588        let value = if !guest
3589            .config()
3590            .backend
3591            .requires_thread_directed_process_signals
3592        {
3593            self.send_guest_signal(
3594                guest,
3595                call,
3596                tid,
3597                call.sig(),
3598                Some(DetPid::from_raw(process)),
3599                false,
3600                DetTid::from_raw(tgid),
3601            )
3602            .await?
3603        } else {
3604            let targeted = syscalls::RtTgsigqueueinfo::new()
3605                .with_tgid(process)
3606                .with_tid(tid.as_raw())
3607                .with_sig(call.sig())
3608                .with_siginfo(call.siginfo());
3609            self.send_guest_signal(
3610                guest,
3611                targeted,
3612                tid,
3613                call.sig(),
3614                Some(DetPid::from_raw(process)),
3615                false,
3616                DetTid::from_raw(tgid),
3617            )
3618            .await?
3619        };
3620        self.notify_cross_task_signal(
3621            guest,
3622            tid,
3623            call.sig(),
3624            Some(DetPid::from_raw(process)),
3625            crate::tool_global::SignalScope::Process,
3626        )
3627        .await;
3628        Ok(value)
3629    }
3630
3631    // AUTONOMOUS-BOT-IMPLEMENTED
3632    // TODO-HUMAN-REVIEW(#663)
3633    /// Read the kernel pending-signal mask after Detcore has serialized all signal
3634    /// generation and delivery events that can change it.
3635    pub async fn handle_rt_sigpending<G: Guest<Self>>(
3636        &self,
3637        guest: &mut G,
3638        call: syscalls::RtSigpending,
3639    ) -> Result<i64, Error> {
3640        // Signal phase 1 refuses rt_sigpending in a process that handles
3641        // SIGALRM (`sigalrm_phase1`), so the ledger's entry never needs to be
3642        // shown here. The pending set would show a real-time timer expiration
3643        // that every thread blocked when it expired, which the kernel never
3644        // queued (https://github.com/rrnewton/hermit/issues/4089).
3645        let pending = pending_real_time_among(guest, REAL_TIME_SIGNALS).await;
3646        act_on_pending_real_time(guest, pending, REAL_TIME_SIGNALS, 0).await;
3647        Ok(self.record_or_replay(guest, call).await?)
3648    }
3649
3650    /// A delivered signal may run a handler, whose return restores, through an
3651    /// `rt_sigreturn` that ptrace does not stop at, a mask Detcore cannot read
3652    /// here: the thread's own mask, or for a handler that interrupts a call
3653    /// with a temporary mask, the mask saved before the call. So every
3654    /// delivery records every real-time signal as possibly unblocked by a
3655    /// handler's return (`Scheduler::handler_restore_unblocked`), and a
3656    /// real-time timer expiration of the process is never kept pending after
3657    /// it (https://github.com/rrnewton/hermit/issues/4089). Only where real-time
3658    /// expirations are kept pending at all (`models_signal_targets`), and once
3659    /// per thread.
3660    pub(crate) async fn record_handler_restore_mask<G: Guest<Self>>(
3661        &self,
3662        guest: &mut G,
3663        signal: SigWrapper,
3664    ) {
3665        if !bundled_signal_facts::models_signal_targets(&self.cfg)
3666            || guest.thread_state().handler_restore_rt_reported == REAL_TIME_SIGNALS
3667        {
3668            return;
3669        }
3670        // Only a caught signal runs a handler that returns. The dispositions
3671        // are the process's, so they say that whatever mask the delivery
3672        // interrupted; a signal acted on by default (the teardown's own
3673        // termination signals among them) records nothing.
3674        let caught =
3675            match crate::syscalls::signal_shadow::copied_dispositions_for(guest, signal.raw()) {
3676                Some(copied) => Ok(copied.caught),
3677                None => read_thread_wait_signal_state(guest.pid(), guest.tid())
3678                    .map(|state| state.caught),
3679            };
3680        if let Ok(caught) = caught
3681            && caught & kernel_sigset_bit(signal.raw()) == 0
3682        {
3683            return;
3684        }
3685        let Some(detpid) = guest.thread_state().detpid else {
3686            return;
3687        };
3688        crate::tool_global::record_handler_restore_mask(guest, detpid, REAL_TIME_SIGNALS).await;
3689        guest.thread_state_mut().handler_restore_rt_reported = REAL_TIME_SIGNALS;
3690    }
3691
3692    /// rt_sigreturn: the mask it restores, from the frame's `uc_sigmask`, may
3693    /// unblock a pending real-time timer expiration that every thread blocked
3694    /// when it expired, which the kernel then delivers as the call returns
3695    /// (https://github.com/rrnewton/hermit/issues/4089). The call itself
3696    /// passes through.
3697    pub(crate) async fn observe_sigreturn_mask<G: Guest<Self>>(&self, guest: &mut G) {
3698        let pending = pending_real_time_among(guest, REAL_TIME_SIGNALS).await;
3699        if pending == 0 {
3700            return;
3701        }
3702        // x86-64 `rt_sigreturn` reads `frame = sp - sizeof(long)` and restores
3703        // `frame->uc.uc_sigmask`; `uc` starts at `sp`.
3704        let sp = guest.regs().await.rsp as usize;
3705        let restored = Addr::<u64>::from_raw(sp.wrapping_add(UC_SIGMASK_OFFSET))
3706            .and_then(|addr| guest.memory().read_value(addr).ok());
3707        let (observable, discarded) = match (
3708            restored,
3709            read_thread_wait_signal_state(guest.pid(), guest.tid()),
3710        ) {
3711            (Some(mask), Ok(state)) => unblocked_by(&state, mask),
3712            // A frame the kernel cannot read either kills the guest with
3713            // SIGSEGV, which delivers nothing pending.
3714            (None, _) => (0, 0),
3715            // A state that cannot be read could hide any delivery.
3716            (Some(_), Err(_)) => (REAL_TIME_SIGNALS, 0),
3717        };
3718        act_on_pending_real_time(guest, pending, observable, discarded).await;
3719    }
3720}
3721
3722/// What [`Detcore::rt_sigprocmask_inner`] knows of the set the kernel used.
3723enum ValidatedSet {
3724    /// The kernel read and accepted this set before Detcore injected the call.
3725    Validated(KernelSigset),
3726    /// Detcore injected nothing: its own read of the set failed first.
3727    NotRun,
3728    /// The call ran as the guest made it; only the kernel read its set.
3729    NotValidated,
3730}
3731
3732/// The offset of `uc_sigmask` in the x86-64 kernel `ucontext` that
3733/// `rt_sigreturn` restores: after uc_flags (8), uc_link (8), uc_stack (24) and
3734/// uc_mcontext (256 bytes).
3735pub(super) const UC_SIGMASK_OFFSET: usize = 8 + 8 + 24 + 256;
3736
3737fn should_notify_cross_task_signal(sender: DetTid, target: DetTid, raw_signal: i32) -> bool {
3738    raw_signal != 0 && target != sender
3739}
3740
3741/// Which check [`sleep_signal`] makes for an emulated `pause` or `nanosleep`.
3742#[derive(Clone, Debug, Eq, PartialEq)]
3743pub(crate) enum SleepCheck {
3744    /// Before the sleep parks: whether a signal already pending for the thread
3745    /// ends it at once.
3746    BeforePark,
3747    /// After the scheduler woke the sleep for these signals.
3748    AfterWake(Option<Vec<SigWrapper>>),
3749}
3750
3751/// What ends an emulated `pause` or `nanosleep`, per [`sleep_signal`].
3752#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3753pub(crate) enum SleepSignal {
3754    /// A signal pending for this thread, unblocked and caught or acted on by
3755    /// default: the kernel delivers it as the call returns. `pause` returns
3756    /// `ERESTARTNOHAND` for it and `nanosleep` `EINTR`.
3757    Pending,
3758    /// The scheduler woke the sleep for a held signal of its own that ends it
3759    /// (`held_wake_ends_sleep`), or this backend does not report the guest's
3760    /// signal state: the call returns `EINTR`, as every wake did before.
3761    Held,
3762    /// Nothing ends the sleep, and it waits (again) with its original deadline.
3763    None,
3764    /// The scheduler's `SIGCHLD`, in a process whose send window is unusable,
3765    /// that this thread claimed (`claim_pending_sigchld`): it is held for
3766    /// delivery to this thread as it resumes, so a signal is always pending
3767    /// then. Each call returns its restart code, as Linux's does: `EINTR` when
3768    /// a handler runs, whatever its `SA_RESTART`, and a restart when none does
3769    /// (the child-exit ledger drops a duplicate copy). `pause` and an absolute
3770    /// `clock_nanosleep` return `ERESTARTNOHAND`, and the kernel re-executes
3771    /// them. A relative `nanosleep` returns `ERESTART_RESTARTBLOCK` and keeps
3772    /// its deadline for the kernel's `restart_syscall`, which only a restart
3773    /// makes (`helpers::RestartCall::Nanosleep`).
3774    Claimed,
3775}
3776
3777/// Decides, in this thread's own turn, whether a signal ends an emulated
3778/// `pause` or `nanosleep` (<https://github.com/rrnewton/hermit/issues/3982>).
3779///
3780/// Only on a backend whose kernel reports the guest's signal state; on any
3781/// other, a sleep never checks before it parks, and a wake always ends it
3782/// (`Held`). A signal ends the sleep when it is pending for this thread,
3783/// unblocked, and caught or acted on by default
3784/// (`KernelSignalState::pending_interrupting`). Before the sleep parks, a stop
3785/// signal does so only when `stops_end_it`, which `nanosleep` leaves unset
3786/// because Detcore does not keep its deadline for the kernel's restart after a
3787/// stop, so the stop takes effect when the sleep ends, as before. After a wake,
3788/// which only the scheduler's own sends (a timer, a child-exit `SIGCHLD`) can
3789/// commit for a stop on a `nanosleep`, a pending stop ends it, as every wake
3790/// did before, so that the stop takes effect promptly.
3791///
3792/// `SIGCHLD` and the signals a host-timed source armed by a guest can post
3793/// (`host_timed_signals`) are held: the kernel can post them at a moment set by
3794/// host timing, and `/proc` cannot tell that copy from one a guest sent. They
3795/// never end a sleep before it parks, nor does the scheduler record a guest's
3796/// cross-task send of one for a sleep. A wake the scheduler committed for its
3797/// own child-exit `SIGCHLD` ends the sleep with `Held` only while the copy it
3798/// sent is still pending in the process's shared queue
3799/// (`ChildExitSigchldControl::PlacedPending`, which `/proc` cannot answer),
3800/// `/proc` shows it pending, and it is unblocked and caught or default-fatal
3801/// (`held_wake_ends_sleep`); a host-timed held signal, from the mask and
3802/// dispositions alone. Like the precise futex
3803/// wait's check, this reads the pending set before the sleep parks as well as
3804/// after a wake: a signal sent while the thread was stopped short of filing
3805/// its request, as when its timeslice ended in the syscall's prehook, is
3806/// pending and was never recorded for its sleep. After a wake whose
3807/// non-held signals are no longer pending, a `SIGCONT` having cancelled a stop
3808/// or `sigaction(SIG_IGN)` having flushed it, a Linux sleep would still be
3809/// asleep, so this returns `None`.
3810///
3811/// A state that cannot be read is handled as a wait's first read is
3812/// (`read_wait_signal_state`, here `read_thread_wait_signal_state`, since
3813/// Reverie can report the creator's pid for a process a raw `clone` made): a
3814/// thread that no longer exists ends the call
3815/// with `ERESTARTNOINTR`, which nothing observes, and otherwise the run ends
3816/// with a diagnostic.
3817pub(crate) async fn sleep_signal<G, T>(
3818    guest: &mut G,
3819    check: SleepCheck,
3820    stops_end_it: bool,
3821) -> Result<SleepSignal, Error>
3822where
3823    G: Guest<Detcore<T>>,
3824    T: RecordOrReplay,
3825{
3826    if !guest
3827        .config()
3828        .backend
3829        .supports_blocked_wait_signal_interruption
3830    {
3831        return Ok(match check {
3832            SleepCheck::BeforePark => SleepSignal::None,
3833            SleepCheck::AfterWake(_) => SleepSignal::Held,
3834        });
3835    }
3836    let host_timed = host_timed_signals(guest).await;
3837    let held = kernel_sigset_bit(libc::SIGCHLD) | host_timed;
3838    let before_park = check == SleepCheck::BeforePark;
3839    // `held_woken`: the held signals the scheduler woke this sleep for.
3840    // `unknown_held_wake`: a wake that names no signal.
3841    let (deciding, held_woken, unknown_held_wake) = match check {
3842        SleepCheck::BeforePark => (!held, 0, false),
3843        SleepCheck::AfterWake(None) => (0, 0, true),
3844        SleepCheck::AfterWake(Some(woken)) => {
3845            let woken = woken
3846                .iter()
3847                .fold(0, |set, signal| set | kernel_sigset_bit(signal.raw()));
3848            (woken & !held, woken & held, false)
3849        }
3850    };
3851    if deciding != 0 || held_woken != 0 {
3852        let state = read_thread_wait_signal_state(guest.pid(), guest.tid())?;
3853        let mut ending = state.pending_interrupting(state.blocked, false) & deciding;
3854        if !stops_end_it && before_park {
3855            ending &= !(state.default_job_control_stops() | kernel_sigset_bit(libc::SIGSTOP));
3856        }
3857        // A copy Linux discarded when it was sent ends nothing, except a
3858        // signal the scheduler committed at the wake, which is kept
3859        // (<https://github.com/rrnewton/hermit/issues/4293>).
3860        let committed = if before_park { 0 } else { deciding };
3861        let ending =
3862            crate::syscalls::threads::without_discarded(guest, &state, ending, committed).await;
3863        if ending != 0 {
3864            return Ok(SleepSignal::Pending);
3865        }
3866        // A committed `SIGCHLD` counts only while the schedule says this thread
3867        // will take it (`PlacedPending`): a guest's thread-directed copy in its
3868        // private queue, or the scheduler's or a guest's shared copy still in
3869        // the window. `/proc` cannot tell either from a kernel copy that host
3870        // timing posted, so its bits only prompt the question: a woken sleep
3871        // asks for the `SIGCHLD` it was woken for, and any sleep asks when its
3872        // private queue holds one, which a guest sent before it parked
3873        // (https://github.com/rrnewton/hermit/issues/4132).
3874        let sigchld = kernel_sigset_bit(libc::SIGCHLD) & !host_timed;
3875        let committed = if asks_committed_sigchld(held_woken, &state, sigchld)
3876            && matches!(
3877                crate::tool_global::child_exit_sigchld(
3878                    guest,
3879                    crate::scheduler::child_exit_sigchld::ChildExitSigchldControl::PlacedPending,
3880                )
3881                .await,
3882                crate::scheduler::child_exit_sigchld::ChildExitSigchldAnswer::Placed(true)
3883            ) {
3884            // A committed copy shows in `/proc`: an invariant, not a second
3885            // condition.
3886            if state.pending & sigchld == 0 {
3887                tracing::error!(
3888                    "[dtid {}] a committed SIGCHLD is pending by the schedule but not in /proc",
3889                    guest.thread_state().dettid
3890                );
3891                debug_assert!(false, "a committed SIGCHLD is not pending in /proc");
3892            }
3893            sigchld
3894        } else {
3895            0
3896        };
3897        if let Some(verdict) = committed_sigchld_verdict(&state, held_woken, committed) {
3898            return Ok(verdict);
3899        }
3900        // Where the process does not use the send window, a thread outside the
3901        // schedule could take the scheduler's copy at a moment host timing
3902        // chooses, so the window records none, and `PlacedPending` says no
3903        // whether or not that thread took it. Parked again, the sleep ran to its
3904        // deadline with the copy pending and the handler ran as it returned, an
3905        // outcome Linux never gives (https://github.com/rrnewton/hermit/issues/4229).
3906        // So this thread claims the copy itself, in its own turn
3907        // (`claim_pending_sigchld`), while SIGCHLD is the signal its kernel
3908        // dequeues next: held for delivery to it, where no other thread can
3909        // take it, so the handler runs as the sleep returns (`Claimed`). If the
3910        // outside thread took it first, the claim finds none and the sleep
3911        // parks again, as on Linux, where the woken sleeper finds no signal. Reading the pending bit and then ending the sleep
3912        // left a gap in which the outside thread could take it, and then the
3913        // sleep returned EINTR with no handler
3914        // (https://github.com/rrnewton/hermit/issues/4341).
3915        //
3916        // In record and replay too, but only while no other thread of the
3917        // process is outside the schedule in a call that could take the copy
3918        // (`Scheduler::outside_call_may_take_sigchld`, through
3919        // `WindowUnusable`). Then nothing but this claim can take it, so its
3920        // pending bit, and the claim, are the same in a recording and its
3921        // replay (https://github.com/rrnewton/hermit/issues/4343). While such a
3922        // call is out, whether it took the copy is host-timed, and replay
3923        // serves a signalfd read from the log without taking anything, so the
3924        // two could decide differently; the sleep parks again, as before.
3925        if committed == 0
3926            && held_woken & sigchld != 0
3927            && woken_sigchld_pending(&state, sigchld)
3928            && matches!(
3929                crate::tool_global::child_exit_sigchld(
3930                    guest,
3931                    crate::scheduler::child_exit_sigchld::ChildExitSigchldControl::WindowUnusable,
3932                )
3933                .await,
3934                crate::scheduler::child_exit_sigchld::ChildExitSigchldAnswer::Placed(true)
3935            )
3936            && state.next_dequeued(state.blocked).map(|(signal, _)| signal) == Some(libc::SIGCHLD)
3937            && {
3938                send_claim_fault_signal(guest, ClaimFault::Usr1BeforeClaim);
3939                let claimed = claim_pending_sigchld(guest).await?;
3940                if claimed {
3941                    send_claim_fault_signal(guest, ClaimFault::Usr1AfterClaim);
3942                }
3943                claimed
3944            }
3945        {
3946            // Its delivery stop places it, so it is not deferred behind a
3947            // runnable sibling (`ThreadState::claimed_sigchld`).
3948            guest.thread_state_mut().claimed_sigchld = true;
3949            return Ok(SleepSignal::Claimed);
3950        }
3951        let held_woken = held_woken & !sigchld;
3952        if held_wake_ends_sleep(&state, held_woken) {
3953            return Ok(SleepSignal::Held);
3954        }
3955        return Ok(SleepSignal::None);
3956    }
3957    Ok(if unknown_held_wake {
3958        SleepSignal::Held
3959    } else {
3960        SleepSignal::None
3961    })
3962}
3963
3964/// Whether this backend's `rt_sigsuspend` returns at once rather than sleeping
3965/// until a signal arrives (`Detcore::handle_rt_sigsuspend`). Reverie names no
3966/// capability for it, so this derives it from the one that implies it: a
3967/// backend that owns guest signal delivery (`provides_process_signal_control`,
3968/// KVM) implements the call itself, and its scheduler-modeled wake does not
3969/// exist, so it returns EINTR for a signal already pending under the temporary
3970/// mask and refuses a wait for one that is not (ENOSYS) rather than parking
3971/// the vCPU outside the schedule. Every other backend runs the kernel's call,
3972/// which sleeps. `rt_sigsuspend_never_sleeps_per_backend` pins the answer for
3973/// every backend Reverie defines; a backend that gains a sleeping
3974/// `rt_sigsuspend` must change it.
3975pub(crate) fn rt_sigsuspend_never_sleeps(backend: &reverie::BackendCapabilities) -> bool {
3976    backend.provides_process_signal_control
3977}
3978
3979/// Whether a `SIGCHLD` this thread claimed (`ThreadState::claimed_sigchld`,
3980/// `claimed`) is still claimed at a syscall entry, or after a `SIGCHLD` the
3981/// ledger dropped: SIGCHLD is still pending in its queue or its process's,
3982/// whatever its mask. The claim may have held another signal instead
3983/// (https://github.com/rrnewton/hermit/issues/4346), whose handler can block
3984/// SIGCHLD and make syscalls before its `rt_sigreturn` lets SIGCHLD be
3985/// delivered (the Codex review of the claimed-delivery fix), or a duplicate
3986/// the ledger drops while another copy waits (the Claude review).
3987/// Once SIGCHLD is not pending, its delivery never came to this thread. A
3988/// state that cannot be read (`read_state`, asked only for a claim) forgets
3989/// the claim, so the delivery is deferred as before the claim existed.
3990pub(crate) fn claim_still_pending<E>(
3991    claimed: bool,
3992    read_state: impl FnOnce() -> Result<crate::syscalls::threads::KernelSignalState, E>,
3993) -> bool {
3994    claimed && read_state().is_ok_and(|state| state.pending & kernel_sigset_bit(libc::SIGCHLD) != 0)
3995}
3996
3997/// Whether `sigchld`, the scheduler's copy a sleep was woken for, is still
3998/// pending for it and ends it: in the thread's or its process's queue, and
3999/// unblocked and caught or acted on by default (`sleep_signal`, for a process
4000/// whose send window is unusable).
4001fn woken_sigchld_pending(
4002    state: &crate::syscalls::threads::KernelSignalState,
4003    sigchld: KernelSigset,
4004) -> bool {
4005    state.pending & state.interrupting(state.blocked) & sigchld != 0
4006}
4007
4008/// Whether a sleep's own check (`sleep_signal`) asks the scheduler whether a
4009/// committed `SIGCHLD` is pending for it (`PlacedPending`): it was woken for
4010/// one (`held_woken`), or its private queue holds one. The latter is how a
4011/// guest's thread-directed copy sent before the sleeper filed its request is
4012/// not lost: the sender's turn found no sleep to wake, so only the sleeper's
4013/// check before it parks sees it (https://github.com/rrnewton/hermit/issues/4132).
4014fn asks_committed_sigchld(
4015    held_woken: KernelSigset,
4016    state: &crate::syscalls::threads::KernelSignalState,
4017    sigchld: KernelSigset,
4018) -> bool {
4019    (held_woken | state.thread_pending) & sigchld != 0
4020}
4021
4022/// What a committed `SIGCHLD` (`committed`, the scheduler's answer) makes of
4023/// the sleep: it ends it if unblocked and caught or acted on by default, as
4024/// the held signal the wake named (`Held`) or as one pending for it
4025/// (`Pending`); `None` leaves the decision to the rest of the check.
4026fn committed_sigchld_verdict(
4027    state: &crate::syscalls::threads::KernelSignalState,
4028    held_woken: KernelSigset,
4029    committed: KernelSigset,
4030) -> Option<SleepSignal> {
4031    let verdict = if held_woken & committed != 0 {
4032        SleepSignal::Held
4033    } else {
4034        SleepSignal::Pending
4035    };
4036    (state.interrupting(state.blocked) & committed != 0).then_some(verdict)
4037}
4038
4039/// The size of a `struct signalfd_siginfo`, which has ssi_signo at 0,
4040/// ssi_code at 8, ssi_pid at 12, ssi_uid at 16, ssi_status at 40, ssi_int at
4041/// 44, ssi_utime at 56 and ssi_stime at 64.
4042pub(crate) const SIGNALFD_RECORD: usize = 128;
4043
4044/// The signals signalfd `fd` of process `pid` reads, from its `sigmask:`
4045/// line in `/proc/<pid>/fdinfo/<fd>` (a kernel sigset in hex), or `None`
4046/// when it cannot be read.
4047pub(crate) fn signalfd_mask(pid: i32, fd: i32) -> Option<u64> {
4048    let info = std::fs::read_to_string(format!("/proc/{pid}/fdinfo/{fd}")).ok()?;
4049    info.lines()
4050        .find_map(|line| line.strip_prefix("sigmask:"))
4051        .and_then(|mask| u64::from_str_radix(mask.trim(), 16).ok())
4052}
4053
4054fn signalfd_field(record: &[u8], at: usize) -> u32 {
4055    u32::from_ne_bytes(record[at..at + 4].try_into().expect("four bytes"))
4056}
4057
4058/// For each `signalfd_siginfo` record in `bytes`, the child-exit ledger
4059/// question it raises (`Detcore::reconcile_signalfd_records`): a SIGCHLD with
4060/// a child-exit code is the kernel's copy for that child, a SIGCHLD the
4061/// scheduler sent (`is_own_sigchld_mark`) is its copy, and any other record
4062/// raises none.
4063fn signalfd_record_controls(
4064    bytes: &[u8],
4065    tracer: u32,
4066) -> Vec<Option<crate::scheduler::child_exit_sigchld::ChildExitSigchldControl>> {
4067    use crate::scheduler::child_exit_sigchld::ChildExitSigchldControl;
4068    use crate::scheduler::child_exit_sigchld::DequeuedCopy;
4069    bytes
4070        .chunks(SIGNALFD_RECORD)
4071        .map(|record| {
4072            if signalfd_field(record, 0) != libc::SIGCHLD as u32 {
4073                return None;
4074            }
4075            let code = signalfd_field(record, 8) as i32;
4076            let pid = signalfd_field(record, 12);
4077            let value = signalfd_field(record, 44) as i32;
4078            let copy = if crate::scheduler::child_exit_sigchld::is_child_exit_code(code) {
4079                DequeuedCopy::Kernel {
4080                    child: DetPid::from_raw(pid as i32),
4081                }
4082            } else if crate::scheduler::child_exit_sigchld::is_own_sigchld_mark(
4083                code, pid as i32, value, tracer,
4084            ) {
4085                DequeuedCopy::Scheduler
4086            } else if code == libc::SI_TKILL {
4087                DequeuedCopy::Thread
4088            } else {
4089                DequeuedCopy::Other
4090            };
4091            // Read, a kept record makes no `InboundSignal` request.
4092            Some(ChildExitSigchldControl::Dequeue {
4093                copy,
4094                admits: false,
4095            })
4096        })
4097        .collect()
4098}
4099
4100/// The pieces of the guest buffers `extents` (address, length) that hold the
4101/// first `len` bytes a vectored read scattered, in order; empty extents are
4102/// skipped.
4103pub(crate) fn signalfd_extent_pieces(
4104    extents: &[(usize, usize)],
4105    len: usize,
4106) -> Vec<(usize, usize)> {
4107    let mut left = len;
4108    let mut pieces = Vec::new();
4109    for (address, length) in extents {
4110        if left == 0 {
4111            break;
4112        }
4113        let take = (*length).min(left);
4114        if take > 0 {
4115            pieces.push((*address, take));
4116            left -= take;
4117        }
4118    }
4119    pieces
4120}
4121
4122/// Signalfd records rewritten by the child-exit ledger's answers.
4123#[derive(Debug, PartialEq, Eq)]
4124struct RewrittenSignalfdRecords {
4125    /// The buffer to write back: the kept records in order, then what the
4126    /// buffer held before the read over the bytes of dropped ones, so no
4127    /// dropped record stays readable.
4128    bytes: Vec<u8>,
4129    /// How many bytes the read returns.
4130    kept: usize,
4131}
4132
4133/// Apply the ledger's `answers`, one per record of `bytes`
4134/// (`signalfd_record_controls`): a claimed duplicate or a duplicate scheduler
4135/// copy is dropped, a copy that stands for an owned child is given that
4136/// child's siginfo with zero CPU times, and every other record is kept as read.
4137/// `Ok(None)` when no record changed. `Err(())` when a record is dropped but
4138/// `before`, the buffer's bytes captured before the read
4139/// (`capture_signalfd_buffer`), does not cover the bytes it leaves: they are
4140/// never invented (the Codex re-check of
4141/// https://github.com/rrnewton/hermit/pull/4351, P2-2).
4142fn apply_signalfd_answers(
4143    bytes: &[u8],
4144    answers: &[Option<crate::scheduler::child_exit_sigchld::ChildExitSigchldAnswer>],
4145    before: &[u8],
4146) -> Result<Option<RewrittenSignalfdRecords>, ()> {
4147    use crate::scheduler::child_exit_sigchld::ChildExitSigchldAnswer;
4148    use crate::scheduler::child_exit_sigchld::OwnCopy;
4149    let mut kept = Vec::with_capacity(bytes.len());
4150    let mut changed = false;
4151    for (record, answer) in bytes.chunks(SIGNALFD_RECORD).zip(answers) {
4152        let mut record = record.to_vec();
4153        match answer {
4154            Some(ChildExitSigchldAnswer::Claimed(true))
4155            | Some(ChildExitSigchldAnswer::OwnCopy(OwnCopy::Duplicate)) => {
4156                changed = true;
4157                continue;
4158            }
4159            Some(ChildExitSigchldAnswer::OwnCopy(OwnCopy::Deliver(own)))
4160            | Some(ChildExitSigchldAnswer::ClaimedFor(own)) => {
4161                // The record Linux writes for a child exit (SIL_CHLD) starts
4162                // zeroed and fills in only these: nothing of the copy it
4163                // replaces is kept, such as the own copy's SI_QUEUE mark in
4164                // ssi_int and ssi_ptr. CPU times are 0 (natively, host time).
4165                let signo = signalfd_field(&record, 0);
4166                record.fill(0);
4167                record[0..4].copy_from_slice(&signo.to_ne_bytes());
4168                record[8..12].copy_from_slice(&own.code.to_ne_bytes());
4169                record[12..16].copy_from_slice(&(own.pid as u32).to_ne_bytes());
4170                record[16..20].copy_from_slice(&own.uid.to_ne_bytes());
4171                record[40..44].copy_from_slice(&own.status.to_ne_bytes());
4172                changed = true;
4173            }
4174            _ => {}
4175        }
4176        kept.extend_from_slice(&record);
4177    }
4178    if !changed {
4179        return Ok(None);
4180    }
4181    let kept_len = kept.len();
4182    let len = bytes.len() - bytes.len() % SIGNALFD_RECORD;
4183    // The bytes past the kept records are those the caller's buffer held
4184    // before the read: a dropped record must leave the buffer as Linux, which
4185    // never queued it, leaves it (https://github.com/rrnewton/hermit/issues/4293).
4186    if before.len() < len {
4187        return Err(());
4188    }
4189    kept.extend_from_slice(&before[kept_len..len]);
4190    Ok(Some(RewrittenSignalfdRecords {
4191        bytes: kept,
4192        kept: kept_len,
4193    }))
4194}
4195
4196#[cfg(test)]
4197mod signalfd_record_tests {
4198    use super::*;
4199    use crate::scheduler::child_exit_sigchld::ChildExitSigchldAnswer;
4200    use crate::scheduler::child_exit_sigchld::ChildExitSigchldControl;
4201    use crate::scheduler::child_exit_sigchld::ChildExitSiginfo;
4202    use crate::scheduler::child_exit_sigchld::OwnCopy;
4203
4204    const TRACER: u32 = 4242;
4205
4206    /// `apply_signalfd_answers` with a captured buffer of zeros, so a dropped
4207    /// record's bytes become zeros.
4208    fn apply_without_capture(
4209        bytes: &[u8],
4210        answers: &[Option<ChildExitSigchldAnswer>],
4211    ) -> Option<RewrittenSignalfdRecords> {
4212        apply_signalfd_answers(bytes, answers, &vec![0; bytes.len()]).unwrap()
4213    }
4214
4215    /// A record dropped where the capture does not reach (a buffer past
4216    /// `SIGNALFD_CAPTURED`) is refused, never given invented bytes (the Codex
4217    /// re-check of https://github.com/rrnewton/hermit/pull/4351, P2-2).
4218    #[test]
4219    fn a_dropped_record_past_the_capture_is_refused() {
4220        let mut bytes = vec![0u8; 2 * SIGNALFD_RECORD];
4221        bytes[0..4].copy_from_slice(&10u32.to_ne_bytes());
4222        bytes[SIGNALFD_RECORD..SIGNALFD_RECORD + 4].copy_from_slice(&12u32.to_ne_bytes());
4223        let before = vec![0xa5u8; SIGNALFD_RECORD];
4224        assert_eq!(
4225            apply_signalfd_answers(
4226                &bytes,
4227                &[Some(ChildExitSigchldAnswer::Claimed(true)), None],
4228                &before,
4229            ),
4230            Err(())
4231        );
4232        // Nothing dropped needs no capture.
4233        assert_eq!(apply_signalfd_answers(&bytes, &[None, None], &[]), Ok(None));
4234    }
4235
4236    /// A dropped record's bytes get what the buffer held before the read.
4237    #[test]
4238    fn a_dropped_record_leaves_the_captured_bytes() {
4239        let record = |signo: u32| {
4240            let mut bytes = vec![0u8; SIGNALFD_RECORD];
4241            bytes[0..4].copy_from_slice(&signo.to_ne_bytes());
4242            bytes
4243        };
4244        let bytes = [record(10), record(12)].concat();
4245        let before = vec![0xa5u8; 2 * SIGNALFD_RECORD];
4246        let rewritten = apply_signalfd_answers(
4247            &bytes,
4248            &[Some(ChildExitSigchldAnswer::Claimed(true)), None],
4249            &before,
4250        )
4251        .unwrap()
4252        .unwrap();
4253        assert_eq!(rewritten.kept, SIGNALFD_RECORD);
4254        assert_eq!(&rewritten.bytes[..SIGNALFD_RECORD], &record(12)[..]);
4255        assert!(
4256            rewritten.bytes[SIGNALFD_RECORD..]
4257                .iter()
4258                .all(|byte| *byte == 0xa5)
4259        );
4260    }
4261
4262    fn record(signo: i32, code: i32, pid: u32, status: i32) -> Vec<u8> {
4263        let mut record = vec![0u8; SIGNALFD_RECORD];
4264        record[0..4].copy_from_slice(&(signo as u32).to_ne_bytes());
4265        record[8..12].copy_from_slice(&code.to_ne_bytes());
4266        record[12..16].copy_from_slice(&pid.to_ne_bytes());
4267        record[40..44].copy_from_slice(&status.to_ne_bytes());
4268        record[56..72].fill(7);
4269        record
4270    }
4271
4272    /// At a receiver in a nested PID namespace, a record of the scheduler's
4273    /// marked `SI_QUEUE` copy (pid 0, `ssi_int` the mark) is its own copy; an
4274    /// ancestor's `SI_USER` from pid 0 and an unmarked `SI_QUEUE` are another
4275    /// (<https://github.com/rrnewton/hermit/issues/4155>).
4276    #[test]
4277    fn a_nested_receivers_marked_record_asks_for_the_own_copy() {
4278        use crate::scheduler::child_exit_sigchld::DequeuedCopy;
4279        let marked = |value: i32| {
4280            let mut record = record(libc::SIGCHLD, libc::SI_QUEUE, 0, 0);
4281            record[44..48].copy_from_slice(&value.to_ne_bytes());
4282            record
4283        };
4284        let bytes = [
4285            marked(crate::scheduler::child_exit_sigchld::OWN_SIGCHLD_MARK),
4286            marked(7),
4287            record(libc::SIGCHLD, libc::SI_USER, 0, 0),
4288        ]
4289        .concat();
4290        let dequeue = |copy| {
4291            Some(ChildExitSigchldControl::Dequeue {
4292                copy,
4293                admits: false,
4294            })
4295        };
4296        assert_eq!(
4297            signalfd_record_controls(&bytes, TRACER),
4298            vec![
4299                dequeue(DequeuedCopy::Scheduler),
4300                dequeue(DequeuedCopy::Other),
4301                dequeue(DequeuedCopy::Other),
4302            ]
4303        );
4304    }
4305
4306    /// Each `SIGCHLD` record from the shared queue tells the ledger it was
4307    /// taken, as which copy: a kernel child-exit copy names its child, the
4308    /// scheduler's `SI_USER` copy is its own, a guest's `SI_USER` is another,
4309    /// and a `SI_TKILL` copy is thread-directed; any other signal asks nothing.
4310    /// A read makes no `InboundSignal` request (`admits` unset).
4311    #[test]
4312    fn each_record_asks_the_ledger_only_about_a_child_exit_copy() {
4313        use crate::scheduler::child_exit_sigchld::DequeuedCopy;
4314        let bytes = [
4315            record(libc::SIGCHLD, libc::CLD_KILLED, 31, libc::SIGKILL),
4316            record(libc::SIGCHLD, libc::SI_USER, TRACER, 0),
4317            record(libc::SIGCHLD, libc::SI_USER, 77, 0),
4318            record(libc::SIGCHLD, libc::SI_TKILL, 77, 0),
4319            record(libc::SIGUSR1, libc::SI_USER, TRACER, 0),
4320        ]
4321        .concat();
4322        let dequeue = |copy| {
4323            Some(ChildExitSigchldControl::Dequeue {
4324                copy,
4325                admits: false,
4326            })
4327        };
4328        assert_eq!(
4329            signalfd_record_controls(&bytes, TRACER),
4330            vec![
4331                dequeue(DequeuedCopy::Kernel {
4332                    child: DetPid::from_raw(31)
4333                }),
4334                dequeue(DequeuedCopy::Scheduler),
4335                dequeue(DequeuedCopy::Other),
4336                dequeue(DequeuedCopy::Thread),
4337                None,
4338            ]
4339        );
4340    }
4341
4342    /// A dropped record leaves the read, the records after it move up, and
4343    /// zeros cover its old bytes; a standing copy gets its owned child's
4344    /// siginfo, a cohort's lowest pid included (`ClaimedFor`), with zero CPU
4345    /// times.
4346    #[test]
4347    fn dropped_records_leave_and_standing_ones_take_the_ledgers_siginfo() {
4348        let own = |pid| ChildExitSiginfo {
4349            code: libc::CLD_KILLED,
4350            pid,
4351            uid: 0,
4352            status: libc::SIGKILL,
4353        };
4354        let first = record(libc::SIGCHLD, libc::CLD_KILLED, 31, libc::SIGKILL);
4355        let second = record(libc::SIGCHLD, libc::SI_USER, TRACER, 0);
4356        let third = record(libc::SIGCHLD, libc::CLD_KILLED, 33, libc::SIGKILL);
4357        let bytes = [first, second, third].concat();
4358        let rewritten = apply_without_capture(
4359            &bytes,
4360            &[
4361                Some(ChildExitSigchldAnswer::Claimed(true)),
4362                Some(ChildExitSigchldAnswer::OwnCopy(OwnCopy::Deliver(own(32)))),
4363                Some(ChildExitSigchldAnswer::ClaimedFor(own(30))),
4364            ],
4365        )
4366        .expect("records changed");
4367        assert_eq!(rewritten.kept, 2 * SIGNALFD_RECORD);
4368        assert_eq!(rewritten.bytes.len(), 3 * SIGNALFD_RECORD);
4369        let expect = |pid: u32| {
4370            let mut wanted = record(libc::SIGCHLD, libc::CLD_KILLED, pid, libc::SIGKILL);
4371            wanted[56..72].fill(0);
4372            wanted
4373        };
4374        assert_eq!(&rewritten.bytes[..SIGNALFD_RECORD], &expect(32)[..]);
4375        assert_eq!(
4376            &rewritten.bytes[SIGNALFD_RECORD..2 * SIGNALFD_RECORD],
4377            &expect(30)[..]
4378        );
4379        assert!(
4380            rewritten.bytes[2 * SIGNALFD_RECORD..]
4381                .iter()
4382                .all(|byte| *byte == 0)
4383        );
4384    }
4385
4386    /// The marked own copy a nested receiver reads is rewritten to the
4387    /// record Linux writes for a child exit, which keeps nothing of the
4388    /// copy: `ssi_int` and `ssi_ptr` (bytes 44..56), where the mark was, are
4389    /// 0, like every field a child exit does not fill in (Codex re-check #2
4390    /// of https://github.com/rrnewton/hermit/pull/4172).
4391    #[test]
4392    fn a_rewritten_own_copy_keeps_none_of_its_marked_record() {
4393        let mut marked = record(libc::SIGCHLD, libc::SI_QUEUE, 0, 0);
4394        marked[44..48]
4395            .copy_from_slice(&crate::scheduler::child_exit_sigchld::OWN_SIGCHLD_MARK.to_ne_bytes());
4396        marked[48..56].fill(9);
4397        marked[20..40].fill(5);
4398        marked[72..].fill(6);
4399        let rewritten = apply_without_capture(
4400            &marked,
4401            &[Some(ChildExitSigchldAnswer::OwnCopy(OwnCopy::Deliver(
4402                ChildExitSiginfo {
4403                    code: libc::CLD_KILLED,
4404                    pid: 3,
4405                    uid: 0,
4406                    status: libc::SIGKILL,
4407                },
4408            )))],
4409        )
4410        .expect("records changed");
4411        let mut wanted = vec![0u8; SIGNALFD_RECORD];
4412        wanted[0..4].copy_from_slice(&(libc::SIGCHLD as u32).to_ne_bytes());
4413        wanted[8..12].copy_from_slice(&libc::CLD_KILLED.to_ne_bytes());
4414        wanted[12..16].copy_from_slice(&3u32.to_ne_bytes());
4415        wanted[40..44].copy_from_slice(&libc::SIGKILL.to_ne_bytes());
4416        assert_eq!(rewritten.bytes, wanted);
4417        assert!(rewritten.bytes[44..56].iter().all(|byte| *byte == 0));
4418    }
4419
4420    /// A vectored read's returned bytes are found across its buffers in
4421    /// order, a record split between two buffers included, and only as far
4422    /// as the read returned.
4423    #[test]
4424    fn a_vectored_reads_records_are_found_across_its_buffers() {
4425        let extents = [(0x1000, 100), (0x2000, 0), (0x3000, 200), (0x4000, 128)];
4426        assert_eq!(
4427            signalfd_extent_pieces(&extents, 256),
4428            vec![(0x1000, 100), (0x3000, 156)]
4429        );
4430        assert_eq!(
4431            signalfd_extent_pieces(&extents, 428),
4432            vec![(0x1000, 100), (0x3000, 200), (0x4000, 128)]
4433        );
4434        assert_eq!(signalfd_extent_pieces(&extents, 0), vec![]);
4435    }
4436
4437    /// A read whose every record is dropped returns nothing and leaves only
4438    /// zeros; a read the ledger leaves alone is not rewritten.
4439    #[test]
4440    fn a_fully_dropped_read_leaves_no_record_and_an_untouched_read_is_not_rewritten() {
4441        let bytes = [
4442            record(libc::SIGCHLD, libc::CLD_KILLED, 31, libc::SIGKILL),
4443            record(libc::SIGCHLD, libc::SI_USER, TRACER, 0),
4444        ]
4445        .concat();
4446        let rewritten = apply_without_capture(
4447            &bytes,
4448            &[
4449                Some(ChildExitSigchldAnswer::Claimed(true)),
4450                Some(ChildExitSigchldAnswer::OwnCopy(OwnCopy::Duplicate)),
4451            ],
4452        )
4453        .expect("records changed");
4454        assert_eq!(rewritten.kept, 0);
4455        assert!(rewritten.bytes.iter().all(|byte| *byte == 0));
4456        assert_eq!(
4457            apply_without_capture(
4458                &bytes,
4459                &[
4460                    Some(ChildExitSigchldAnswer::Claimed(false)),
4461                    Some(ChildExitSigchldAnswer::OwnCopy(OwnCopy::Unowned)),
4462                ],
4463            ),
4464            None
4465        );
4466    }
4467}
4468
4469/// The signals a thread may send to its own multi-threaded process with `kill`
4470/// or `rt_sigqueueinfo` (https://github.com/rrnewton/hermit/issues/4034): each
4471/// is numbered below SIGCHLD, so a child-exit SIGCHLD, whenever the kernel
4472/// posts it, is dequeued after it; none is in the kernel's synchronous set
4473/// (`SYNCHRONOUS_MASK`); and none is a signal Reverie gives a meaning
4474/// (SIGTRAP, its stop signal, and SIGSTKFLT, its timer marker).
4475const OWN_PROCESS_SIGNALS: [libc::c_int; 7] = [
4476    libc::SIGHUP,
4477    libc::SIGINT,
4478    libc::SIGQUIT,
4479    libc::SIGUSR1,
4480    libc::SIGUSR2,
4481    libc::SIGPIPE,
4482    libc::SIGTERM,
4483];
4484
4485/// Why a process-directed signal a thread sends to its own multi-threaded
4486/// process is refused, each a named refusal of the design for
4487/// https://github.com/rrnewton/hermit/issues/4034.
4488#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4489pub(crate) enum OwnProcessSignalRefusal {
4490    /// The signal is not one of `OWN_PROCESS_SIGNALS`.
4491    SignalNotAdmitted,
4492    /// The process leaves the signal at its default, fatal, disposition.
4493    DefaultDisposition,
4494    /// The run records or replays.
4495    RecordReplay,
4496    /// The run replays a recorded schedule (`--replay-schedule-from`).
4497    ScheduleReplay,
4498    /// A guest has sent SIGSTKFLT, which Reverie uses as its timer marker.
4499    GuestMarkerSignal,
4500    /// `--stacktrace-signal` is configured.
4501    StacktraceSignal,
4502    /// The sender blocks the signal.
4503    SenderBlocks,
4504    /// A thread of the process runs or sleeps outside the schedule.
4505    OutOfSchedule(DetTid),
4506    /// A thread of the process has an unknown mask.
4507    UnknownMask(DetTid),
4508    /// The sender is not the thread the call names, and a live thread does
4509    /// not block the signal.
4510    NotSoleReceiver(DetTid),
4511    /// The sender's private queue holds these signals, which it does not block.
4512    PrivatePending(u64),
4513    /// These host-timed sources, which the sender does not block, are armed.
4514    HostTimedSource(u64),
4515    /// Unreaped children have these exit signals, which the sender does not block.
4516    ForeignExitSignal(u64),
4517    /// The scheduler sent these signals, at or below the one sent, and no
4518    /// thread has taken them yet.
4519    UndeliveredSchedulerSignal(u64),
4520    /// A happens-before anchor is set on this call's completion.
4521    PosthookAnchor,
4522    /// The process holds a signalfd.
4523    Signalfd,
4524    /// An exec is in flight in the process.
4525    ExecInFlight,
4526}
4527
4528impl std::fmt::Display for OwnProcessSignalRefusal {
4529    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4530        match self {
4531            Self::SignalNotAdmitted => write!(
4532                f,
4533                "only SIGHUP, SIGINT, SIGQUIT, SIGUSR1, SIGUSR2, SIGPIPE and SIGTERM are delivered \
4534                 deterministically to the sender"
4535            ),
4536            Self::DefaultDisposition => write!(
4537                f,
4538                "the signal has its default disposition, which ends the process"
4539            ),
4540            Self::RecordReplay => write!(f, "the run records or replays"),
4541            Self::ScheduleReplay => write!(
4542                f,
4543                "the run replays a recorded schedule (--replay-schedule-from), whose trace turn \
4544                 after the send can hand the turn to another thread"
4545            ),
4546            Self::GuestMarkerSignal => write!(
4547                f,
4548                "a guest sent SIGSTKFLT, which Reverie also uses as its timer marker, so a pending \
4549                 copy cannot be told from Reverie's"
4550            ),
4551            Self::StacktraceSignal => write!(f, "--stacktrace-signal is configured"),
4552            Self::SenderBlocks => write!(f, "the sending thread blocks the signal"),
4553            Self::OutOfSchedule(tid) => write!(
4554                f,
4555                "thread {tid} runs or sleeps outside the schedule, at moments host timing sets"
4556            ),
4557            Self::UnknownMask(tid) => write!(f, "thread {tid}'s signal mask is unknown"),
4558            Self::NotSoleReceiver(tid) => write!(
4559                f,
4560                "thread {tid} does not block the signal, so Linux could give it to either thread"
4561            ),
4562            Self::PrivatePending(set) => write!(
4563                f,
4564                "the sending thread has signals pending ({set:#x}) that it would take first"
4565            ),
4566            Self::HostTimedSource(set) => write!(
4567                f,
4568                "a source that sends signals {set:#x} at moments host timing sets is armed"
4569            ),
4570            Self::ForeignExitSignal(set) => write!(
4571                f,
4572                "a child with exit signal {set:#x} is unreaped, and the kernel sends that signal at \
4573                 a moment host timing sets"
4574            ),
4575            Self::UndeliveredSchedulerSignal(set) => write!(
4576                f,
4577                "the scheduler sent signals {set:#x} that no thread has taken yet"
4578            ),
4579            Self::PosthookAnchor => {
4580                write!(f, "a happens-before anchor is set on the call's completion")
4581            }
4582            Self::Signalfd => write!(f, "the process holds a signalfd"),
4583            Self::ExecInFlight => write!(f, "an exec is in flight in the process"),
4584        }
4585    }
4586}
4587
4588/// Everything a process-directed signal `sig` that a thread sends to its own
4589/// multi-threaded process is decided from, all fixed by the schedule at the
4590/// sender's turn (`own_process_signal_refusal`).
4591#[derive(Clone, Debug, Default)]
4592pub(crate) struct OwnProcessSignal {
4593    pub(crate) sig: libc::c_int,
4594    /// Whether the call names the sender itself (S1 of the design).
4595    pub(crate) names_sender: bool,
4596    /// The sender's mask (`SigBlk`).
4597    pub(crate) blocked: u64,
4598    /// The sender's private queue (`SigPnd`).
4599    pub(crate) thread_pending: u64,
4600    /// The process's `SIG_IGN` dispositions (`SigIgn`).
4601    pub(crate) ignored: u64,
4602    /// The process's handlers (`SigCgt`).
4603    pub(crate) caught: u64,
4604    pub(crate) inputs: OwnProcessSignalInputs,
4605    pub(crate) record_replay: bool,
4606    pub(crate) schedule_replay: bool,
4607    pub(crate) stacktrace_signal: bool,
4608    pub(crate) posthook_anchor: bool,
4609    pub(crate) signalfd: bool,
4610}
4611
4612/// The refusal for `send`, or `None` when the kernel's choice of receiver and
4613/// the sender's dequeue are forced: the sender takes the signal on its way back
4614/// to user mode, before any other thread of the process can run
4615/// (https://github.com/rrnewton/hermit/issues/4034).
4616pub(crate) fn own_process_signal_refusal(
4617    send: &OwnProcessSignal,
4618) -> Option<OwnProcessSignalRefusal> {
4619    use OwnProcessSignalRefusal as R;
4620    let bit = kernel_sigset_bit(send.sig);
4621    if !OWN_PROCESS_SIGNALS.contains(&send.sig) {
4622        return Some(R::SignalNotAdmitted);
4623    }
4624    if (send.ignored | send.caught) & bit == 0 {
4625        return Some(R::DefaultDisposition);
4626    }
4627    if send.record_replay {
4628        return Some(R::RecordReplay);
4629    }
4630    if send.schedule_replay {
4631        return Some(R::ScheduleReplay);
4632    }
4633    if send.stacktrace_signal {
4634        return Some(R::StacktraceSignal);
4635    }
4636    if send.blocked & bit != 0 {
4637        return Some(R::SenderBlocks);
4638    }
4639    for (tid, state) in &send.inputs.siblings {
4640        if *state == SiblingSignalState::OutOfSchedule {
4641            return Some(R::OutOfSchedule(*tid));
4642        }
4643    }
4644    for (tid, state) in &send.inputs.siblings {
4645        if *state == SiblingSignalState::InSchedule(None) {
4646            return Some(R::UnknownMask(*tid));
4647        }
4648    }
4649    if !send.names_sender {
4650        for (tid, state) in &send.inputs.siblings {
4651            if matches!(state, SiblingSignalState::InSchedule(Some(mask)) if mask & bit == 0) {
4652                return Some(R::NotSoleReceiver(*tid));
4653            }
4654        }
4655    }
4656    let unblocked = !send.blocked;
4657    let private = without_perf_event_signal(send.thread_pending) & unblocked;
4658    if private != 0 {
4659        return Some(R::PrivatePending(private));
4660    }
4661    let host_timed = send.inputs.host_timed & unblocked;
4662    if host_timed != 0 {
4663        return Some(R::HostTimedSource(host_timed));
4664    }
4665    let foreign = send.inputs.foreign_exit_signals & unblocked;
4666    if foreign != 0 {
4667        return Some(R::ForeignExitSignal(foreign));
4668    }
4669    // A signal numbered at or below `sig` is dequeued first or coalesces.
4670    let at_or_below = bit | (bit - 1);
4671    let undelivered = send.inputs.undelivered_scheduler_signals & unblocked & at_or_below;
4672    if undelivered != 0 {
4673        return Some(R::UndeliveredSchedulerSignal(undelivered));
4674    }
4675    if send.posthook_anchor {
4676        return Some(R::PosthookAnchor);
4677    }
4678    if send.signalfd {
4679        return Some(R::Signalfd);
4680    }
4681    if send.inputs.exec_in_flight {
4682        return Some(R::ExecInFlight);
4683    }
4684    if send.inputs.guest_marker_signal {
4685        return Some(R::GuestMarkerSignal);
4686    }
4687    None
4688}
4689
4690/// How a process-directed signal the calling thread sends goes on
4691/// (`Detcore::own_process_signal`).
4692/// What a positive pid the calling thread names refers to
4693/// (`Detcore::name_guest_pid`).
4694enum NamedGuestPid {
4695    /// This task, by its DetTid. `own_init_caught` is set when it belongs to
4696    /// the caller's own PID namespace's init, to the signals that init catches.
4697    Task {
4698        task: DetTid,
4699        own_init_caught: Option<u64>,
4700    },
4701    /// The call's answer, decided here: ESRCH for a pid no task of the
4702    /// caller's namespace has, or a refusal by name.
4703    Answer(Result<i64, Error>),
4704}
4705
4706enum OwnProcessSend {
4707    /// The call does not name the sender's own multi-threaded process: the
4708    /// ordinary path decides.
4709    NotOwn,
4710    /// Admitted: forward the call unchanged, holding the sender's turn.
4711    Admitted,
4712    /// Refused by name, with the policy's answer.
4713    Refused(Result<i64, Error>),
4714}
4715
4716/// What `Detcore::rt_sigqueueinfo_precheck` found.
4717enum RtSigqueueinfoPrecheck {
4718    /// The kernel fails the call without sending (EPERM, or E2BIG, after a
4719    /// complete copy): forward it unchanged.
4720    KernelFails,
4721    /// The kernel's copy certainly faults: Hermit answers EFAULT itself.
4722    Efault,
4723    /// The call goes on to admission.
4724    Proceeds,
4725    /// Hermit cannot read the whole `siginfo_t`, and cannot prove that the
4726    /// kernel's copy faults: `[vvar]`, which neither tracer read reaches; a
4727    /// tail running into a gap; a first 48 bytes in the gap below a grow-down
4728    /// mapping, which the kernel's copy may grow into; or an unreadable
4729    /// `/proc/<tid>/smaps`.
4730    Unreadable,
4731}
4732
4733/// One mapping of a `/proc/<pid>/smaps` listing.
4734#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4735struct Mapping {
4736    start: usize,
4737    end: usize,
4738    /// Whether user mode can read it: on x86 any of read, write or execute
4739    /// permission allows a read; none (`---`) faults.
4740    user_readable: bool,
4741    /// `VmFlags` `gd`: a fault just below it can grow it downwards.
4742    growsdown: bool,
4743}
4744
4745/// The mappings of a `/proc/<pid>/smaps` listing, in address order.
4746fn parse_smaps(smaps: &str) -> Vec<Mapping> {
4747    let mut mappings: Vec<Mapping> = Vec::new();
4748    for line in smaps.lines() {
4749        if let Some(flags) = line.strip_prefix("VmFlags:") {
4750            if let Some(last) = mappings.last_mut() {
4751                last.growsdown = flags.split_whitespace().any(|flag| flag == "gd");
4752            }
4753            continue;
4754        }
4755        let mut fields = line.split_whitespace();
4756        let Some((start, end)) = fields.next().and_then(|range| range.split_once('-')) else {
4757            continue;
4758        };
4759        let (Ok(start), Ok(end), Some(perms)) = (
4760            usize::from_str_radix(start, 16),
4761            usize::from_str_radix(end, 16),
4762            fields.next(),
4763        ) else {
4764            continue;
4765        };
4766        if perms.len() < 4 {
4767            continue;
4768        }
4769        mappings.push(Mapping {
4770            start,
4771            end,
4772            user_readable: perms.chars().take(3).any(|perm| perm != '-'),
4773            growsdown: false,
4774        });
4775    }
4776    mappings.sort_by_key(|mapping| mapping.start);
4777    mappings
4778}
4779
4780/// Why a byte is not readable by user mode (`first_user_unreadable`).
4781#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4782enum Unreadable {
4783    /// In a mapping without read, write or execute permission.
4784    NoPermission,
4785    /// In no mapping; `below_growsdown` when the next mapping above it can
4786    /// grow down into it.
4787    Hole { below_growsdown: bool },
4788}
4789
4790/// Where the first byte of `[address, address + len)` that user mode cannot
4791/// read lies, or `None` when user mode can read them all. A range that
4792/// overflows the address space counts as a hole.
4793fn first_user_unreadable(mappings: &[Mapping], address: usize, len: usize) -> Option<Unreadable> {
4794    let Some(end) = address.checked_add(len) else {
4795        return Some(Unreadable::Hole {
4796            below_growsdown: false,
4797        });
4798    };
4799    let mut next = address;
4800    while next < end {
4801        match mappings.iter().find(|mapping| mapping.end > next) {
4802            Some(mapping) if mapping.start <= next => {
4803                if !mapping.user_readable {
4804                    return Some(Unreadable::NoPermission);
4805                }
4806                next = mapping.end;
4807            }
4808            above => {
4809                return Some(Unreadable::Hole {
4810                    below_growsdown: above.is_some_and(|mapping| mapping.growsdown),
4811                });
4812            }
4813        }
4814    }
4815    None
4816}
4817
4818/// The signals a send of `sig` lets Linux send later at a moment set by host
4819/// timing, as a kernel sigset; 0 for every signal but the four that stop by
4820/// default. A stopped member makes its process group one that an exit can
4821/// orphan with a stopped job, and Linux then sends that whole group SIGHUP and
4822/// SIGCONT at the exiting process's physical exit (`kill_orphaned_pgrp` in
4823/// kernel/exit.c). Apart from a guest's send, only a terminal stops a guest
4824/// process, and a terminal's signals, these two among them, are recorded with
4825/// `terminal_signals`.
4826fn orphaned_group_signals(sig: libc::c_int) -> u64 {
4827    match sig {
4828        libc::SIGSTOP | libc::SIGTSTP | libc::SIGTTIN | libc::SIGTTOU => {
4829            kernel_sigset_bit(libc::SIGHUP) | kernel_sigset_bit(libc::SIGCONT)
4830        }
4831        _ => 0,
4832    }
4833}
4834
4835/// Whether a held signal the scheduler woke a sleep for (`held_woken`, a
4836/// child-exit `SIGCHLD`) ends it: as Linux delivery would, only when this
4837/// thread's mask leaves it unblocked and it is caught or acted on by default
4838/// (`KernelSignalState::interrupting`). A blocked one stays pending, and a
4839/// default-ignored one (`SIGCHLD` without a handler) is discarded, and either
4840/// way the sleep goes on (https://github.com/rrnewton/hermit/issues/4126).
4841///
4842/// The caller has already removed a committed `SIGCHLD` that no longer counts:
4843/// the scheduler sends it to the process, so the kernel gives it to whichever
4844/// thread resumes first without blocking it, and a schedule may run a sibling
4845/// first (`--chaos-target-races`). Taken by that sibling, it is gone from the
4846/// child-exit ledger's send window (`ChildExitSigchldControl::PlacedPending`),
4847/// and the sleep goes on to its original deadline, as a futex wait woken for a
4848/// signal waits again (`futex_wait_held_after_wake`). Answering EINTR for it
4849/// anyway was a result Linux cannot give: the call interrupted, the handler run
4850/// in another thread (the Claude re-check of
4851/// https://github.com/rrnewton/hermit/pull/4131). A held signal a host-timed
4852/// source can also post is decided from the mask and dispositions alone.
4853fn held_wake_ends_sleep(
4854    state: &crate::syscalls::threads::KernelSignalState,
4855    held_woken: KernelSigset,
4856) -> bool {
4857    state.interrupting(state.blocked) & held_woken != 0
4858}
4859
4860#[cfg(test)]
4861mod tests {
4862    /// A first probe's not-run report restarts the call; any other result,
4863    /// errno or value, passes through unchanged.
4864    #[test]
4865    fn a_first_probe_not_run_restarts_the_call() {
4866        let restart = |result: Result<u64, Error>| restart_if_first_probe_not_run(result);
4867        assert!(matches!(
4868            restart(Err(Errno::ERESTARTSYS.into())),
4869            Err(Error::Errno(Errno::ERESTARTNOINTR))
4870        ));
4871        for errno in [
4872            Errno::EFAULT,
4873            Errno::EINVAL,
4874            Errno::EINTR,
4875            Errno::ERESTARTNOHAND,
4876        ] {
4877            assert!(
4878                matches!(restart(Err(errno.into())), Err(Error::Errno(e)) if e == errno),
4879                "{errno} passes through"
4880            );
4881        }
4882        assert!(matches!(restart(Ok(7)), Ok(7)));
4883    }
4884
4885    use super::*;
4886
4887    fn timeval(seconds: libc::time_t, micros: libc::suseconds_t) -> libc::timeval {
4888        libc::timeval {
4889            tv_sec: seconds,
4890            tv_usec: micros,
4891        }
4892    }
4893
4894    /// Only KVM's `rt_sigsuspend` returns at once, so only there does the call
4895    /// run in the caller's own turn (https://github.com/rrnewton/hermit/issues/4360).
4896    /// Every other backend runs the kernel's sleeping call outside the
4897    /// runnable set.
4898    #[test]
4899    fn rt_sigsuspend_never_sleeps_per_backend() {
4900        use reverie::BackendCapabilities;
4901        for (name, backend, never_sleeps) in [
4902            ("ptrace", BackendCapabilities::PTRACE, false),
4903            ("e9patch", BackendCapabilities::E9PATCH, false),
4904            ("kvm", BackendCapabilities::KVM, true),
4905            ("sabre", BackendCapabilities::SABRE, false),
4906            ("dbt", BackendCapabilities::DBT, false),
4907            (
4908                "liteinst in-guest",
4909                BackendCapabilities::LITEINST_IN_GUEST,
4910                false,
4911            ),
4912        ] {
4913            assert_eq!(rt_sigsuspend_never_sleeps(&backend), never_sleeps, "{name}");
4914        }
4915    }
4916
4917    /// A send of each of the four default-stop signals arms the orphaned
4918    /// process group's SIGHUP and SIGCONT; no other signal arms anything.
4919    #[test]
4920    fn only_a_default_stop_signal_arms_the_orphaned_group_signals() {
4921        let hup_cont = kernel_sigset_bit(libc::SIGHUP) | kernel_sigset_bit(libc::SIGCONT);
4922        for sig in 0..=65 {
4923            let stops = matches!(
4924                sig,
4925                libc::SIGSTOP | libc::SIGTSTP | libc::SIGTTIN | libc::SIGTTOU
4926            );
4927            assert_eq!(
4928                orphaned_group_signals(sig),
4929                if stops { hup_cont } else { 0 },
4930                "signal {sig}"
4931            );
4932        }
4933    }
4934
4935    /// A child-exit `SIGCHLD` the scheduler woke a sleep for ends it only when
4936    /// it is unblocked and caught: blocked, or with its default (ignore)
4937    /// action, the sleep goes on, as on Linux
4938    /// (https://github.com/rrnewton/hermit/issues/4126). Taken by a sibling
4939    /// first, it is no longer among the held signals the wake counts, and the
4940    /// sleep goes on too (the Claude re-check of
4941    /// https://github.com/rrnewton/hermit/pull/4131). A default-fatal held
4942    /// signal (a host-timed `SIGALRM` without a handler) ends it.
4943    #[test]
4944    fn a_held_wake_ends_a_sleep_only_when_unblocked_and_caught_or_fatal() {
4945        use crate::syscalls::threads::KernelSignalState;
4946        let chld = kernel_sigset_bit(libc::SIGCHLD);
4947        let alrm = kernel_sigset_bit(libc::SIGALRM);
4948        let state = |caught: KernelSigset, blocked: KernelSigset| KernelSignalState {
4949            caught,
4950            blocked,
4951            ..Default::default()
4952        };
4953        assert!(held_wake_ends_sleep(&state(chld, 0), chld));
4954        assert!(!held_wake_ends_sleep(&state(chld, chld), chld));
4955        assert!(!held_wake_ends_sleep(&state(0, 0), chld));
4956        assert!(held_wake_ends_sleep(&state(0, 0), alrm));
4957        assert!(!held_wake_ends_sleep(&state(0, alrm), alrm));
4958        assert!(
4959            !held_wake_ends_sleep(&state(chld, 0), 0),
4960            "taken by a sibling"
4961        );
4962    }
4963
4964    /// In a process whose send window is unusable, a sleep woken for the
4965    /// scheduler's `SIGCHLD` ends for it when the copy is still pending, in its
4966    /// process's queue or its own, and unblocked and caught. It parks again
4967    /// when another thread took the copy, its mask blocks it, or it is left at
4968    /// its default action, which ignores it
4969    /// (https://github.com/rrnewton/hermit/issues/4229).
4970    #[test]
4971    fn a_woken_sleep_counts_a_pending_sigchld_in_an_unusable_window() {
4972        use crate::syscalls::threads::KernelSignalState;
4973        let chld = kernel_sigset_bit(libc::SIGCHLD);
4974        let state =
4975            |caught: KernelSigset, blocked: KernelSigset, shared: KernelSigset| KernelSignalState {
4976                caught,
4977                blocked,
4978                pending: shared,
4979                shared_pending: shared,
4980                ..Default::default()
4981            };
4982        assert!(woken_sigchld_pending(&state(chld, 0, chld), chld));
4983        assert!(
4984            !woken_sigchld_pending(&state(chld, 0, 0), chld),
4985            "another thread took it"
4986        );
4987        assert!(
4988            !woken_sigchld_pending(&state(chld, chld, chld), chld),
4989            "blocked"
4990        );
4991        assert!(
4992            !woken_sigchld_pending(&state(0, 0, chld), chld),
4993            "default, ignored"
4994        );
4995        assert!(
4996            !woken_sigchld_pending(&state(chld, 0, chld), 0),
4997            "host-timed SIGCHLD keeps it held"
4998        );
4999        let private = KernelSignalState {
5000            caught: chld,
5001            pending: chld,
5002            thread_pending: chld,
5003            ..Default::default()
5004        };
5005        assert!(woken_sigchld_pending(&private, chld));
5006    }
5007
5008    /// A claimed `SIGCHLD` stays claimed at a syscall while it is pending for
5009    /// the thread, in either queue: among them the syscall a held SIGUSR1's
5010    /// handler makes while its mask blocks SIGCHLD. It is forgotten once
5011    /// SIGCHLD is not pending, or when the state cannot be read, and an
5012    /// unclaimed thread reads nothing (the Codex review of the
5013    /// claimed-delivery fix; https://github.com/rrnewton/hermit/issues/4346).
5014    #[test]
5015    fn a_claimed_sigchld_stays_claimed_while_pending() {
5016        use crate::syscalls::threads::KernelSignalState;
5017        let chld = kernel_sigset_bit(libc::SIGCHLD);
5018        let usr1 = kernel_sigset_bit(libc::SIGUSR1);
5019        let state = |blocked: KernelSigset, thread_pending: KernelSigset, shared: KernelSigset| {
5020            Ok::<_, Errno>(KernelSignalState {
5021                caught: chld | usr1,
5022                blocked,
5023                pending: thread_pending | shared,
5024                thread_pending,
5025                shared_pending: shared,
5026                ..Default::default()
5027            })
5028        };
5029        assert!(claim_still_pending(true, || state(0, 0, chld)));
5030        assert!(claim_still_pending(true, || state(0, chld, 0)));
5031        assert!(
5032            claim_still_pending(true, || state(chld | usr1, 0, chld)),
5033            "inside the held SIGUSR1's handler, whose mask holds SIGCHLD"
5034        );
5035        assert!(
5036            !claim_still_pending(true, || state(0, 0, usr1)),
5037            "taken elsewhere"
5038        );
5039        assert!(
5040            !claim_still_pending(true, || Err::<KernelSignalState, _>(Errno::ESRCH)),
5041            "unreadable"
5042        );
5043        assert!(
5044            !claim_still_pending(false, || -> Result<KernelSignalState, Errno> {
5045                panic!("an unclaimed thread reads no state")
5046            }),
5047            "unclaimed"
5048        );
5049    }
5050
5051    /// Before it parks, a sleep whose private queue already holds a guest's
5052    /// thread-directed `SIGCHLD` asks whether the copy is committed, and a
5053    /// committed one that is unblocked and caught ends the sleep as pending
5054    /// for it: the copy was sent before the sleeper filed its request, so the
5055    /// sender's turn had no sleep to wake (the Codex review of
5056    /// https://github.com/rrnewton/hermit/pull/4177). Without one, or with no
5057    /// wake and nothing private, it asks nothing; blocked, it does not end the
5058    /// sleep.
5059    #[test]
5060    fn a_private_sigchld_sent_before_the_sleep_is_filed_ends_it_before_it_parks() {
5061        use crate::syscalls::threads::KernelSignalState;
5062        let chld = kernel_sigset_bit(libc::SIGCHLD);
5063        let state = |blocked: KernelSigset, thread_pending: KernelSigset| KernelSignalState {
5064            caught: chld,
5065            blocked,
5066            pending: thread_pending,
5067            thread_pending,
5068            ..Default::default()
5069        };
5070        // Before park: no wake named a signal (`held_woken` 0).
5071        assert!(asks_committed_sigchld(0, &state(0, chld), chld));
5072        assert!(!asks_committed_sigchld(0, &state(0, 0), chld));
5073        assert!(
5074            !asks_committed_sigchld(0, &state(0, chld), 0),
5075            "a host-timed SIGCHLD source keeps it held"
5076        );
5077        assert_eq!(
5078            committed_sigchld_verdict(&state(0, chld), 0, chld),
5079            Some(SleepSignal::Pending)
5080        );
5081        assert_eq!(committed_sigchld_verdict(&state(chld, chld), 0, chld), None);
5082        assert_eq!(committed_sigchld_verdict(&state(0, chld), 0, 0), None);
5083        // After a wake for it, the same copy is the held signal it named.
5084        assert!(asks_committed_sigchld(chld, &state(0, 0), chld));
5085        assert_eq!(
5086            committed_sigchld_verdict(&state(0, chld), chld, chld),
5087            Some(SleepSignal::Held)
5088        );
5089    }
5090
5091    #[test]
5092    fn raw_kernel_signal_masks_are_exactly_one_u64() {
5093        assert_eq!(KERNEL_SIGSET_SIZE, 8);
5094        assert_eq!(std::mem::size_of::<KernelSigset>(), 8);
5095        assert!(std::mem::size_of::<libc::sigset_t>() > KERNEL_SIGSET_SIZE);
5096    }
5097
5098    /// The mask `rt_sigsuspend` (and the scheduler's record of it) sleeps
5099    /// under can never block SIGKILL or SIGSTOP; every other bit is kept.
5100    #[test]
5101    fn the_installed_mask_cannot_block_kill_or_stop() {
5102        let kill = 1_u64 << (libc::SIGKILL - 1);
5103        let stop = 1_u64 << (libc::SIGSTOP - 1);
5104        assert_eq!(kernel_installed_signal_mask(u64::MAX), !(kill | stop));
5105        assert_eq!(kernel_installed_signal_mask(kill | stop), 0);
5106        let alrm_and_rt64 = (1_u64 << (libc::SIGALRM - 1)) | (1_u64 << 63);
5107        assert_eq!(kernel_installed_signal_mask(alrm_and_rt64), alrm_and_rt64);
5108    }
5109
5110    #[test]
5111    fn raw_signal_size_validation_rejects_before_pointer_processing() {
5112        assert_eq!(validate_kernel_sigset_size(7), Err(Errno::EINVAL));
5113        assert_eq!(validate_kernel_sigset_size(8), Ok(()));
5114        assert_eq!(validate_kernel_sigset_size(16), Err(Errno::EINVAL));
5115    }
5116
5117    #[test]
5118    fn reserved_signal_is_removed_from_the_kernel_sized_mask_only() {
5119        let reserved = 1_u64 << (reverie::PERF_EVENT_SIGNAL as u32 - 1);
5120        let usr1 = 1_u64 << (libc::SIGUSR1 as u32 - 1);
5121        assert_eq!(without_perf_event_signal(reserved | usr1), usr1);
5122        assert_eq!(without_perf_event_signal(usr1), usr1);
5123    }
5124
5125    #[test]
5126    fn timeval_conversion_preserves_subsecond_precision() {
5127        let logical_time =
5128            timeval_to_logical_time(timeval(2, 345_678)).expect("valid timeval should convert");
5129        assert_eq!(
5130            logical_time,
5131            LogicalTime::from_nanos(2_345_678_000),
5132            "timeval conversion should preserve microsecond precision"
5133        );
5134
5135        let round_trip = logical_time_to_timeval(logical_time);
5136        assert_eq!(round_trip.tv_sec, 2, "round trip should preserve seconds");
5137        assert_eq!(
5138            round_trip.tv_usec, 345_678,
5139            "round trip should preserve microseconds"
5140        );
5141    }
5142
5143    #[test]
5144    fn timeval_conversion_rejects_invalid_values() {
5145        for invalid in [
5146            timeval(-1, 0),
5147            timeval(0, -1),
5148            timeval(0, 1_000_000),
5149            timeval(libc::time_t::MAX, 0),
5150        ] {
5151            assert_eq!(
5152                timeval_to_logical_time(invalid),
5153                Err(Errno::EINVAL),
5154                "invalid timeval should return EINVAL"
5155            );
5156        }
5157    }
5158
5159    #[test]
5160    fn alarm_seconds_round_as_linux_does() {
5161        assert_eq!(linux_alarm_seconds(LogicalTime::ZERO), 0);
5162        assert_eq!(linux_alarm_seconds(LogicalTime::from_nanos(1)), 1);
5163        assert_eq!(linux_alarm_seconds(LogicalTime::from_nanos(1_000)), 1);
5164        assert_eq!(
5165            linux_alarm_seconds(LogicalTime::from_nanos(1_000_000_000)),
5166            1
5167        );
5168        assert_eq!(
5169            linux_alarm_seconds(LogicalTime::from_nanos(1_499_999_999)),
5170            1
5171        );
5172        assert_eq!(
5173            linux_alarm_seconds(LogicalTime::from_nanos(1_500_000_000)),
5174            2
5175        );
5176        assert_eq!(
5177            linux_alarm_seconds(LogicalTime::from_nanos(2_000_000_001)),
5178            2
5179        );
5180    }
5181
5182    #[test]
5183    fn alarm_remaining_seconds_round_up() {
5184        assert_eq!(logical_time_to_alarm_seconds(LogicalTime::ZERO), 0);
5185        assert_eq!(logical_time_to_alarm_seconds(LogicalTime::from_nanos(1)), 1);
5186        assert_eq!(
5187            logical_time_to_alarm_seconds(LogicalTime::from_nanos(999_999_999)),
5188            1
5189        );
5190        assert_eq!(
5191            logical_time_to_alarm_seconds(LogicalTime::from_nanos(1_000_000_000)),
5192            1
5193        );
5194        assert_eq!(
5195            logical_time_to_alarm_seconds(LogicalTime::from_nanos(1_000_000_001)),
5196            2
5197        );
5198    }
5199
5200    #[test]
5201    fn kill_targets_only_unambiguous_process_delivery() {
5202        let first = DetTid::from_raw(42);
5203        let second = DetTid::from_raw(43);
5204        assert_eq!(
5205            deterministic_kill_target(&[], None, libc::SIGUSR1),
5206            Err(Errno::ESRCH)
5207        );
5208        assert_eq!(
5209            deterministic_kill_target(&[], Some(true), libc::SIGUSR1),
5210            Ok(None)
5211        );
5212        assert_eq!(
5213            deterministic_kill_target(&[], Some(false), libc::SIGUSR1),
5214            Err(Errno::ESRCH)
5215        );
5216        assert_eq!(
5217            deterministic_kill_target(&[first], None, libc::SIGUSR1),
5218            Ok(Some(first))
5219        );
5220        assert_eq!(
5221            deterministic_kill_target(&[first, second], None, libc::SIGUSR1),
5222            Err(Errno::ENOSYS)
5223        );
5224        assert_eq!(
5225            deterministic_kill_target(&[first, second], None, 0),
5226            Ok(Some(first))
5227        );
5228
5229        let process = DetPid::from_raw(41);
5230        assert!(self_sigkill_targets_current_task(
5231            libc::SIGKILL,
5232            Some(process),
5233            None,
5234            process,
5235            first,
5236        ));
5237        assert!(self_sigkill_targets_current_task(
5238            libc::SIGKILL,
5239            None,
5240            Some(first),
5241            process,
5242            first,
5243        ));
5244        assert!(self_sigkill_targets_current_task(
5245            libc::SIGKILL,
5246            Some(process),
5247            Some(first),
5248            process,
5249            first,
5250        ));
5251        for (signal, target_process, target_thread) in [
5252            (libc::SIGTERM, Some(process), Some(first)),
5253            (libc::SIGKILL, Some(DetPid::from_raw(40)), Some(first)),
5254            (libc::SIGKILL, Some(process), Some(second)),
5255            (libc::SIGKILL, None, None),
5256        ] {
5257            assert!(!self_sigkill_targets_current_task(
5258                signal,
5259                target_process,
5260                target_thread,
5261                process,
5262                first,
5263            ));
5264        }
5265    }
5266
5267    #[test]
5268    fn process_group_forwarding_is_limited_to_unmaskable_sigkill() {
5269        assert!(can_forward_process_group_signal(-42, libc::SIGKILL, false));
5270        assert!(!can_forward_process_group_signal(-42, libc::SIGTERM, false));
5271        assert!(!can_forward_process_group_signal(0, libc::SIGKILL, false));
5272        assert!(!can_forward_process_group_signal(-1, libc::SIGKILL, false));
5273        assert!(!can_forward_process_group_signal(-42, libc::SIGKILL, true));
5274    }
5275
5276    #[test]
5277    fn signal_zero_never_notifies_a_target() {
5278        let sender = DetTid::from_raw(42);
5279        let target = DetTid::from_raw(43);
5280        assert!(!should_notify_cross_task_signal(sender, target, 0));
5281        assert!(should_notify_cross_task_signal(
5282            sender,
5283            target,
5284            libc::SIGUSR1
5285        ));
5286        assert!(!should_notify_cross_task_signal(
5287            sender,
5288            sender,
5289            libc::SIGUSR1
5290        ));
5291    }
5292}
5293
5294#[cfg(test)]
5295mod appropriated_signal_tests {
5296    use super::*;
5297
5298    /// The set is closed, and it is closed BY MEASUREMENT: every signal 1..64 was
5299    /// run under two delivery paths against a native control, and exactly these
5300    /// two differ. If a third is ever appropriated it must be added here, because
5301    /// the diagnostic is the only thing that makes the loss visible.
5302    #[test]
5303    fn the_appropriated_set_is_exactly_sigtrap_and_sigstkflt() {
5304        let signums: Vec<i32> = APPROPRIATED_SIGNALS.iter().map(|(s, _)| *s).collect();
5305        assert_eq!(signums, vec![libc::SIGTRAP, libc::SIGSTKFLT]);
5306        // SIGSTKFLT is appropriated because reverie uses it as the PMU timer, so
5307        // the two must not drift apart.
5308        assert_eq!(libc::SIGSTKFLT, reverie::PERF_EVENT_SIGNAL as i32);
5309    }
5310
5311    /// ⚠️ SIG_DFL and SIG_IGN LOSE NOTHING. A guest that is not asking to be
5312    /// called back has no expectation to disappoint, and warning there would make
5313    /// the marker noise instead of signal -- Go registers SIGSTKFLT routinely.
5314    #[test]
5315    fn only_a_real_handler_is_reported() {
5316        for signum in [libc::SIGTRAP, libc::SIGSTKFLT] {
5317            assert!(!reports(signum, 0), "SIG_DFL must not warn");
5318            assert!(!reports(signum, 1), "SIG_IGN must not warn");
5319            assert!(reports(signum, 0x4000_1234), "a real handler must warn");
5320        }
5321    }
5322
5323    /// An ordinary signal is delivered normally and must never be reported.
5324    #[test]
5325    fn an_unappropriated_signal_is_never_reported() {
5326        for signum in [libc::SIGUSR1, libc::SIGTERM, libc::SIGINT, 10, 30] {
5327            assert!(
5328                !reports(signum, 0x4000_1234),
5329                "signal {signum} is not appropriated"
5330            );
5331        }
5332    }
5333
5334    /// Calls the REAL predicate. Deliberately not a re-implementation: a
5335    /// mirrored copy would keep passing if `appropriated_reason` were gutted.
5336    fn reports(signum: i32, handler: u64) -> bool {
5337        appropriated_reason(signum, handler).is_some()
5338    }
5339}
5340
5341#[cfg(test)]
5342mod rt_sigsuspend_tests {
5343    use reverie::GlobalRPC;
5344    use reverie::GlobalTool;
5345    use reverie::Pid;
5346    use reverie::Tool;
5347    use reverie::syscalls::LocalMemory;
5348    use reverie::syscalls::Syscall;
5349    use reverie::syscalls::SyscallInfo;
5350
5351    use super::*;
5352    use crate::Config;
5353    use crate::GlobalState;
5354    use crate::ThreadState;
5355    use crate::syscalls::threads::kernel_sigset_bit;
5356
5357    /// The guest's stack, in this process's memory: `regs` reports a stack
5358    /// pointer `STACK_WORD` words in, so the cells below its red zone are words
5359    /// `COPY_WORD - 1` (the pending set) and `COPY_WORD` (the copy).
5360    const ARENA_WORDS: usize = 64;
5361    const STACK_WORD: usize = 48;
5362    const COPY_WORD: usize = STACK_WORD - STACK_RED_ZONE / 8 - 1;
5363
5364    /// rt_sigsuspend writes its cells directly; it takes no scratch stack.
5365    struct NoStack;
5366
5367    struct NoStackGuard;
5368
5369    impl Drop for NoStackGuard {
5370        fn drop(&mut self) {}
5371    }
5372
5373    impl reverie::Stack for NoStack {
5374        type StackGuard = NoStackGuard;
5375
5376        fn size(&self) -> usize {
5377            panic!("rt_sigsuspend takes no scratch stack")
5378        }
5379        fn capacity(&self) -> usize {
5380            panic!("rt_sigsuspend takes no scratch stack")
5381        }
5382        fn push<'stack, T>(&mut self, _: T) -> Addr<'stack, T> {
5383            panic!("rt_sigsuspend takes no scratch stack")
5384        }
5385        fn reserve<'stack, T>(&mut self) -> AddrMut<'stack, T> {
5386            panic!("rt_sigsuspend takes no scratch stack")
5387        }
5388        fn commit(self) -> Result<Self::StackGuard, Errno> {
5389            panic!("rt_sigsuspend takes no scratch stack")
5390        }
5391    }
5392
5393    /// A guest whose `rt_sigsuspend` caller's mask lives at `caller_mask`. The
5394    /// call's `rt_sigpending` probe, which runs after Detcore read that mask
5395    /// and before the real call, rewrites it to `rewritten` if one is given,
5396    /// as another process sharing the buffer could while the call waits for
5397    /// its turn. Every mask a real `rt_sigsuspend` is given is kept in
5398    /// `suspended_under`.
5399    struct SuspendGuest {
5400        config: Config,
5401        thread: ThreadState<()>,
5402        arena: Box<[u64; ARENA_WORDS]>,
5403        caller_mask: usize,
5404        rewritten: Option<KernelSigset>,
5405        suspended_under: Vec<KernelSigset>,
5406    }
5407
5408    #[reverie::tool]
5409    impl GlobalRPC<GlobalState> for SuspendGuest {
5410        async fn send_rpc(
5411            &self,
5412            message: <GlobalState as GlobalTool>::Request,
5413        ) -> <GlobalState as GlobalTool>::Response {
5414            panic!(
5415                "an unsequentialized rt_sigsuspend sends no RPC: {:?}",
5416                message.2
5417            )
5418        }
5419        fn config(&self) -> &Config {
5420            &self.config
5421        }
5422    }
5423
5424    #[reverie::tool]
5425    impl Guest<Detcore> for SuspendGuest {
5426        type Memory = LocalMemory;
5427        type Stack = NoStack;
5428
5429        fn tid(&self) -> Pid {
5430            Pid::from_raw(1)
5431        }
5432        fn pid(&self) -> Pid {
5433            Pid::from_raw(1)
5434        }
5435        fn ppid(&self) -> Option<Pid> {
5436            None
5437        }
5438        fn memory(&self) -> Self::Memory {
5439            LocalMemory::new()
5440        }
5441        fn thread_state_mut(&mut self) -> &mut ThreadState<()> {
5442            &mut self.thread
5443        }
5444        fn thread_state(&self) -> &ThreadState<()> {
5445            &self.thread
5446        }
5447        async fn regs(&mut self) -> libc::user_regs_struct {
5448            // SAFETY: user_regs_struct is plain integers; all zeroes is valid.
5449            let mut regs: libc::user_regs_struct = unsafe { std::mem::zeroed() };
5450            regs.rsp = (self.arena.as_ptr() as usize + STACK_WORD * 8) as u64;
5451            regs
5452        }
5453        async fn stack(&mut self) -> Self::Stack {
5454            NoStack
5455        }
5456        async fn daemonize(&mut self) {
5457            panic!("rt_sigsuspend must not daemonize")
5458        }
5459        async fn inject<S: SyscallInfo>(&mut self, syscall: S) -> Result<i64, Errno> {
5460            let (number, args) = syscall.into_parts();
5461            match Syscall::from_raw(number, args) {
5462                // read_kernel_sigset's validation probe.
5463                Syscall::RtSigprocmask(call) if call.how() == -1 => Err(Errno::EINVAL),
5464                Syscall::RtSigpending(call) => {
5465                    let set = call.set().expect("rt_sigpending without a set");
5466                    LocalMemory::new().write_value(set.cast::<KernelSigset>(), &0)?;
5467                    if let Some(rewritten) = self.rewritten {
5468                        // SAFETY: `caller_mask` is the test's live, aligned buffer.
5469                        unsafe {
5470                            std::ptr::write(self.caller_mask as *mut KernelSigset, rewritten)
5471                        };
5472                    }
5473                    Ok(0)
5474                }
5475                Syscall::RtSigsuspend(call) => {
5476                    let mask = call.mask().expect("rt_sigsuspend without a mask");
5477                    self.suspended_under
5478                        .push(LocalMemory::new().read_value(mask.cast::<KernelSigset>())?);
5479                    Err(Errno::EINTR)
5480                }
5481                other => panic!("rt_sigsuspend injected {other:?}"),
5482            }
5483        }
5484        async fn tail_inject<S: SyscallInfo>(&mut self, _: S) -> reverie::Never {
5485            panic!("rt_sigsuspend must not retire the guest")
5486        }
5487        fn set_timer(&mut self, _: reverie::TimerSchedule) -> Result<(), Error> {
5488            panic!("rt_sigsuspend must not set a timer")
5489        }
5490        fn set_timer_precise(&mut self, _: reverie::TimerSchedule) -> Result<(), Error> {
5491            panic!("rt_sigsuspend must not set a timer")
5492        }
5493        fn read_clock(&mut self) -> Result<u64, Error> {
5494            panic!("rt_sigsuspend must not read a clock")
5495        }
5496    }
5497
5498    /// The real `rt_sigsuspend` sleeps under the mask Detcore read when it
5499    /// handled the call, the one the scheduler is given, even if the guest's
5500    /// buffer changes before the call runs. Linux copies the mask when the call
5501    /// starts, and from the guest's view it has started. Before, the call ran
5502    /// with the guest's pointer: another process sharing the buffer could make
5503    /// it block a signal the scheduler had counted on to end it, and the
5504    /// scheduler would hold every other thread waiting for that wake.
5505    #[tokio::test(flavor = "current_thread")]
5506    async fn rt_sigsuspend_sleeps_under_the_mask_detcore_read() {
5507        let config = Config::default();
5508        assert!(!config.sequentialize_threads);
5509        let tool = <Detcore as Tool>::new(Pid::from_raw(1), &config);
5510        let unblocks_sigchld: KernelSigset = kernel_sigset_bit(libc::SIGUSR2);
5511        let blocks_sigchld = unblocks_sigchld | kernel_sigset_bit(libc::SIGCHLD);
5512        let mut caller_mask: Box<KernelSigset> = Box::new(unblocks_sigchld);
5513        let caller_address = &mut *caller_mask as *mut KernelSigset as usize;
5514        let mut guest = SuspendGuest {
5515            thread: ThreadState::new(DetPid::from_raw(1), &config, ()),
5516            config: config.clone(),
5517            arena: Box::new([u64::MAX; ARENA_WORDS]),
5518            caller_mask: caller_address,
5519            rewritten: Some(blocks_sigchld),
5520            suspended_under: Vec::new(),
5521        };
5522        let call = syscalls::RtSigsuspend::new()
5523            .with_mask(Addr::from_raw(caller_address))
5524            .with_sigsetsize(KERNEL_SIGSET_SIZE);
5525
5526        let result = tool.handle_rt_sigsuspend(&mut guest, call).await;
5527        assert!(
5528            matches!(result, Err(Error::Errno(Errno::EINTR))),
5529            "{result:?}"
5530        );
5531        assert_eq!(*caller_mask, blocks_sigchld, "the buffer was rewritten");
5532        assert_eq!(guest.suspended_under, [unblocks_sigchld]);
5533    }
5534
5535    /// A caller's mask that lies on the cells Detcore places below the red
5536    /// zone, as a raw syscall may pass one there in a shared stack: the copy
5537    /// must not be the caller's buffer, or a rewrite of the shared buffer
5538    /// reaches the real call again, and the rt_sigpending cell must not
5539    /// overwrite it. The cells move below the buffer, which keeps its own
5540    /// contents. Before, the copy slot was the caller's buffer, and the
5541    /// pending slot's buffer was overwritten with the pending set.
5542    #[tokio::test(flavor = "current_thread")]
5543    async fn rt_sigsuspend_scratch_never_lands_on_the_callers_mask() {
5544        let config = Config::default();
5545        let tool = <Detcore as Tool>::new(Pid::from_raw(1), &config);
5546        let original: KernelSigset = kernel_sigset_bit(libc::SIGUSR2);
5547        let rewritten = original | kernel_sigset_bit(libc::SIGCHLD);
5548        // The copy's slot, rewritten by a peer; then the pending cell's slot,
5549        // which nobody rewrites.
5550        for (slot, peer_rewrite) in [(COPY_WORD, Some(rewritten)), (COPY_WORD - 1, None)] {
5551            let mut arena = Box::new([u64::MAX; ARENA_WORDS]);
5552            arena[slot] = original;
5553            let caller_address = &mut arena[slot] as *mut u64 as usize;
5554            let mut guest = SuspendGuest {
5555                thread: ThreadState::new(DetPid::from_raw(1), &config, ()),
5556                config: config.clone(),
5557                arena,
5558                caller_mask: caller_address,
5559                rewritten: peer_rewrite,
5560                suspended_under: Vec::new(),
5561            };
5562            let call = syscalls::RtSigsuspend::new()
5563                .with_mask(Addr::from_raw(caller_address))
5564                .with_sigsetsize(KERNEL_SIGSET_SIZE);
5565
5566            let result = tool.handle_rt_sigsuspend(&mut guest, call).await;
5567            assert!(
5568                matches!(result, Err(Error::Errno(Errno::EINTR))),
5569                "slot {slot}: {result:?}"
5570            );
5571            assert_eq!(guest.suspended_under, [original], "slot {slot}");
5572            assert_eq!(
5573                guest.arena[slot],
5574                peer_rewrite.unwrap_or(original),
5575                "slot {slot}: the caller's buffer holds only what the guest wrote"
5576            );
5577        }
5578    }
5579}
5580
5581#[cfg(test)]
5582mod before_park_tests {
5583    use reverie::GlobalRPC;
5584    use reverie::GlobalTool;
5585    use reverie::Pid;
5586    use reverie::syscalls::SyscallInfo;
5587
5588    use super::*;
5589    use crate::Config;
5590    use crate::GlobalState;
5591    use crate::ThreadState;
5592    use crate::scheduler::child_exit_sigchld::ChildExitSigchldControl;
5593
5594    /// The before-park check takes no scratch stack.
5595    struct NoStack;
5596
5597    struct NoStackGuard;
5598
5599    impl Drop for NoStackGuard {
5600        fn drop(&mut self) {}
5601    }
5602
5603    impl reverie::Stack for NoStack {
5604        type StackGuard = NoStackGuard;
5605
5606        fn size(&self) -> usize {
5607            panic!("the before-park check takes no stack")
5608        }
5609        fn capacity(&self) -> usize {
5610            panic!("the before-park check takes no stack")
5611        }
5612        fn push<'stack, T>(&mut self, _: T) -> Addr<'stack, T> {
5613            panic!("the before-park check takes no stack")
5614        }
5615        fn reserve<'stack, T>(&mut self) -> AddrMut<'stack, T> {
5616            panic!("the before-park check takes no stack")
5617        }
5618        fn commit(self) -> Result<Self::StackGuard, Errno> {
5619            panic!("the before-park check takes no stack")
5620        }
5621    }
5622
5623    /// A guest whose thread is a real stopped process, so `sleep_signal`
5624    /// reads the kernel's signal state for it from `/proc`, and whose RPCs go
5625    /// to a real `GlobalState`, so its questions reach the scheduler's ledger.
5626    struct SleeperGuest<'a> {
5627        state: &'a GlobalState,
5628        config: Config,
5629        thread: ThreadState<()>,
5630        pid: Pid,
5631    }
5632
5633    #[reverie::tool]
5634    impl GlobalRPC<GlobalState> for SleeperGuest<'_> {
5635        async fn send_rpc(
5636            &self,
5637            request: <GlobalState as GlobalTool>::Request,
5638        ) -> <GlobalState as GlobalTool>::Response {
5639            self.state.receive_rpc(self.pid, request).await
5640        }
5641        fn config(&self) -> &Config {
5642            &self.config
5643        }
5644    }
5645
5646    #[reverie::tool]
5647    impl Guest<Detcore> for SleeperGuest<'_> {
5648        type Memory = reverie::syscalls::LocalMemory;
5649        type Stack = NoStack;
5650
5651        fn tid(&self) -> Pid {
5652            self.pid
5653        }
5654        fn pid(&self) -> Pid {
5655            self.pid
5656        }
5657        fn ppid(&self) -> Option<Pid> {
5658            None
5659        }
5660        fn memory(&self) -> Self::Memory {
5661            panic!("the before-park check reads no guest memory")
5662        }
5663        fn thread_state_mut(&mut self) -> &mut ThreadState<()> {
5664            &mut self.thread
5665        }
5666        fn thread_state(&self) -> &ThreadState<()> {
5667            &self.thread
5668        }
5669        async fn regs(&mut self) -> libc::user_regs_struct {
5670            panic!("the before-park check reads no registers")
5671        }
5672        async fn stack(&mut self) -> Self::Stack {
5673            panic!("the before-park check takes no stack")
5674        }
5675        async fn daemonize(&mut self) {
5676            panic!("the before-park check must not daemonize")
5677        }
5678        async fn inject<S: SyscallInfo>(&mut self, _: S) -> Result<i64, Errno> {
5679            panic!("the before-park check injects no syscall")
5680        }
5681        async fn tail_inject<S: SyscallInfo>(&mut self, _: S) -> reverie::Never {
5682            panic!("the before-park check must not retire the guest")
5683        }
5684        fn set_timer(&mut self, _: reverie::TimerSchedule) -> Result<(), Error> {
5685            panic!("the before-park check sets no timer")
5686        }
5687        fn set_timer_precise(&mut self, _: reverie::TimerSchedule) -> Result<(), Error> {
5688            panic!("the before-park check sets no timer")
5689        }
5690        fn read_clock(&mut self) -> Result<u64, Error> {
5691            panic!("the before-park check reads no clock")
5692        }
5693    }
5694
5695    extern "C" fn caught(_: libc::c_int) {}
5696
5697    /// `waitpid` for exactly `child`, retried on EINTR: the pid and status
5698    /// it reported, or the errno of its failure.
5699    fn wait_for(
5700        child: libc::pid_t,
5701        options: libc::c_int,
5702    ) -> Result<(libc::pid_t, libc::c_int), i32> {
5703        let mut status = 0;
5704        loop {
5705            // SAFETY: waiting for our own child.
5706            let waited = unsafe { libc::waitpid(child, &mut status, options) };
5707            if waited != -1 {
5708                return Ok((waited, status));
5709            }
5710            match std::io::Error::last_os_error().raw_os_error() {
5711                Some(libc::EINTR) => continue,
5712                errno => return Err(errno.unwrap_or(0)),
5713            }
5714        }
5715    }
5716
5717    /// The parent's ownership of the forked child: it is killed and reaped
5718    /// when the owner is dropped, so a panic or a cancelled await in the test
5719    /// leaves no process behind. `finish` does the same on the normal path
5720    /// and checks that the child was reaped.
5721    struct ChildOwner {
5722        pid: libc::pid_t,
5723        reaped: bool,
5724    }
5725
5726    impl ChildOwner {
5727        /// Wait for the child to stop. A wait that reports it exited or
5728        /// killed reaped it, so the owner is disarmed before anything can
5729        /// unwind: its pid may already belong to another process.
5730        /// An ECHILD means the child is no longer ours to wait for (it was
5731        /// reaped already), so it disarms the owner too.
5732        fn wait_stopped(&mut self) -> Result<(), Result<(libc::pid_t, libc::c_int), i32>> {
5733            let waited = wait_for(self.pid, libc::WUNTRACED);
5734            match waited {
5735                Ok((pid, status))
5736                    if pid == self.pid
5737                        && (libc::WIFEXITED(status) || libc::WIFSIGNALED(status)) =>
5738                {
5739                    self.reaped = true;
5740                }
5741                Err(libc::ECHILD) => self.reaped = true,
5742                _ => {}
5743            }
5744            match waited {
5745                Ok((pid, status)) if pid == self.pid && libc::WIFSTOPPED(status) => Ok(()),
5746                other => Err(other),
5747            }
5748        }
5749
5750        /// Whether the owner had disarmed itself, read once the child is
5751        /// known to be reaped. The owner is disarmed from here on whatever
5752        /// the answer, so a failed check of it unwinds without signalling a
5753        /// pid that may have been reused.
5754        fn disarmed_after_reap(&mut self) -> bool {
5755            std::mem::replace(&mut self.reaped, true)
5756        }
5757
5758        fn kill_and_reap(&mut self) -> Result<(libc::pid_t, libc::c_int), i32> {
5759            // SAFETY: killing our own child, which is not yet reaped.
5760            unsafe { libc::kill(self.pid, libc::SIGKILL) };
5761            let reaped = wait_for(self.pid, 0);
5762            self.reaped = true;
5763            reaped
5764        }
5765
5766        fn finish(mut self) {
5767            let reaped = self.kill_and_reap();
5768            assert!(
5769                matches!(reaped, Ok((pid, status)) if pid == self.pid
5770                    && libc::WIFSIGNALED(status)
5771                    && libc::WTERMSIG(status) == libc::SIGKILL),
5772                "the child was not reaped: {reaped:?}"
5773            );
5774        }
5775    }
5776
5777    impl Drop for ChildOwner {
5778        fn drop(&mut self) {
5779            if !self.reaped {
5780                // Unwinding already: the reap's outcome is not checked here.
5781                let _ = self.kill_and_reap();
5782            }
5783        }
5784    }
5785
5786    /// A forked child, owned by the parent from the moment `fork` returns,
5787    /// that exits with status 7 at once if `exits`.
5788    fn forked_child(exits: bool) -> ChildOwner {
5789        // SAFETY: the child calls only async-signal-safe functions, with no
5790        // allocation, lock or destructor, then stops until it is killed.
5791        let child = unsafe { libc::fork() };
5792        if child == 0 {
5793            unsafe {
5794                if exits {
5795                    libc::_exit(7);
5796                }
5797                let mut action: libc::sigaction = std::mem::zeroed();
5798                action.sa_sigaction = caught as extern "C" fn(libc::c_int) as usize;
5799                libc::sigaction(libc::SIGCHLD, &action, std::ptr::null_mut());
5800                let mut set: libc::sigset_t = std::mem::zeroed();
5801                libc::sigemptyset(&mut set);
5802                libc::sigaddset(&mut set, libc::SIGCHLD);
5803                libc::pthread_sigmask(libc::SIG_UNBLOCK, &set, std::ptr::null_mut());
5804                libc::raise(libc::SIGSTOP);
5805                libc::_exit(0);
5806            }
5807        }
5808        assert!(child > 0, "fork failed");
5809        ChildOwner {
5810            pid: child,
5811            reaped: false,
5812        }
5813    }
5814
5815    /// A child stopped as a sleeper is when Detcore handles its call before
5816    /// filing the sleep: SIGCHLD caught and unblocked, and SIGCHLD pending in
5817    /// its private queue, sent to the thread while it was stopped.
5818    fn stopped_child_with_a_private_sigchld() -> ChildOwner {
5819        let mut owner = forked_child(false);
5820        let child = owner.pid;
5821        if let Err(waited) = owner.wait_stopped() {
5822            panic!("the child did not stop: {waited:?}");
5823        }
5824        // SAFETY: the child is ours and stopped; SIGCHLD stays pending.
5825        let sent = unsafe { libc::syscall(libc::SYS_tgkill, child, child, libc::SIGCHLD) };
5826        assert_eq!(sent, 0, "tgkill failed");
5827        owner
5828    }
5829
5830    /// The before-park question through the production path: a guest's
5831    /// thread-directed SIGCHLD, committed (`PrivateSent`, as the sender's turn
5832    /// records it) while no sleep was filed, so that turn had no sleep to
5833    /// wake, is found by `sleep_signal(BeforePark)`'s own query of the ledger,
5834    /// and the sleep ends at once as pending for it. With no committed record
5835    /// the same kernel state, which `/proc` cannot tell from a host-timed copy,
5836    /// ends nothing (the Codex re-check of
5837    /// https://github.com/rrnewton/hermit/pull/4177).
5838    #[tokio::test(flavor = "current_thread")]
5839    async fn a_private_sigchld_committed_before_the_sleep_is_filed_ends_it_through_the_ledger() {
5840        // The fixture's owner: a child that exits instead of stopping is
5841        // reaped by the wait, which disarms the owner, so an unwind then
5842        // signals no pid that may have been reused.
5843        let mut exited = forked_child(true);
5844        let wait = exited.wait_stopped();
5845        let exit_reaped = matches!(wait, Err(Ok((pid, status))) if pid == exited.pid
5846            && libc::WIFEXITED(status)
5847            && libc::WEXITSTATUS(status) == 7);
5848        let disarmed = exit_reaped && exited.disarmed_after_reap();
5849        assert!(exit_reaped, "{wait:?}");
5850        assert!(disarmed, "a reaped child disarms its owner");
5851        drop(exited);
5852        // A child already reaped elsewhere answers ECHILD, which disarms the
5853        // owner as well. The raw wait that reaps it disarms the owner before
5854        // anything is checked; the owner is armed again only for the call
5855        // under test.
5856        let mut gone = forked_child(true);
5857        let reaped_elsewhere = wait_for(gone.pid, 0);
5858        gone.reaped = matches!(reaped_elsewhere, Ok((pid, _)) if pid == gone.pid)
5859            || reaped_elsewhere == Err(libc::ECHILD);
5860        assert!(
5861            matches!(reaped_elsewhere, Ok((pid, _)) if pid == gone.pid),
5862            "{reaped_elsewhere:?}"
5863        );
5864        gone.reaped = false;
5865        let wait = gone.wait_stopped();
5866        let disarmed = gone.disarmed_after_reap();
5867        assert_eq!(wait, Err(Err(libc::ECHILD)));
5868        assert!(disarmed, "an ECHILD disarms its owner");
5869        drop(gone);
5870
5871        let owner = stopped_child_with_a_private_sigchld();
5872        let child = owner.pid;
5873        let state_of_child = crate::syscalls::threads::read_thread_wait_signal_state(
5874            Pid::from_raw(child),
5875            Pid::from_raw(child),
5876        )
5877        .expect("the child's signal state");
5878        let chld = kernel_sigset_bit(libc::SIGCHLD);
5879        assert_eq!(
5880            state_of_child.thread_pending & chld,
5881            chld,
5882            "pending, private"
5883        );
5884        assert_eq!(state_of_child.blocked & chld, 0, "unblocked");
5885        assert_eq!(state_of_child.caught & chld, chld, "caught");
5886        let mut verdicts = Vec::new();
5887        for committed in [true, false] {
5888            let config = Config {
5889                sequentialize_threads: true,
5890                ..Config::default()
5891            }
5892            .with_backend(|backend| {
5893                backend.supports_blocked_wait_signal_interruption = true;
5894                backend.delivers_preemption_timer_events = false;
5895                backend.runs_guest_code_between_injections = false;
5896            });
5897            let state = GlobalState::for_tests(&config);
5898            let mut guest = SleeperGuest {
5899                state: &state,
5900                thread: ThreadState::new(DetPid::from_raw(child), &config, ()),
5901                config,
5902                pid: Pid::from_raw(child),
5903            };
5904            if committed {
5905                let target = guest.thread_state().dettid;
5906                crate::tool_global::child_exit_sigchld(
5907                    &mut guest,
5908                    ChildExitSigchldControl::PrivateSent { target },
5909                )
5910                .await;
5911            }
5912            verdicts.push(sleep_signal(&mut guest, SleepCheck::BeforePark, false).await);
5913        }
5914        owner.finish();
5915        assert!(
5916            matches!(verdicts[0], Ok(SleepSignal::Pending)),
5917            "committed: {:?}",
5918            verdicts[0]
5919        );
5920        assert!(
5921            matches!(verdicts[1], Ok(SleepSignal::None)),
5922            "not committed: {:?}",
5923            verdicts[1]
5924        );
5925    }
5926
5927    /// The futex counterpart: a precise futex wait's own check before it
5928    /// parks (`futex_wait_pending_signals`) finds a guest's thread-directed
5929    /// SIGCHLD committed (`PrivateSent`) before the wait was filed, through
5930    /// the production query of the ledger, and the wait ends with its restart
5931    /// errno. With no record, or when a host-timed source can post SIGCHLD to
5932    /// the process, the same kernel state ends nothing and the wait parks
5933    /// (https://github.com/rrnewton/hermit/issues/4132).
5934    #[tokio::test(flavor = "current_thread")]
5935    async fn a_private_sigchld_committed_before_a_futex_wait_parks_ends_it_through_the_ledger() {
5936        let owner = stopped_child_with_a_private_sigchld();
5937        let child = owner.pid;
5938        let state = crate::syscalls::threads::read_thread_wait_signal_state(
5939            Pid::from_raw(child),
5940            Pid::from_raw(child),
5941        )
5942        .expect("the child's signal state");
5943        let chld = kernel_sigset_bit(libc::SIGCHLD);
5944        let interrupting = state.pending_interrupting(state.blocked, false);
5945        let mut pending = Vec::new();
5946        for (committed, host_timed) in [(true, 0), (false, 0), (true, chld)] {
5947            let config = Config {
5948                sequentialize_threads: true,
5949                ..Config::default()
5950            }
5951            .with_backend(|backend| {
5952                backend.supports_blocked_wait_signal_interruption = true;
5953                backend.delivers_preemption_timer_events = false;
5954                backend.runs_guest_code_between_injections = false;
5955            });
5956            let global = GlobalState::for_tests(&config);
5957            let mut guest = SleeperGuest {
5958                state: &global,
5959                thread: ThreadState::new(DetPid::from_raw(child), &config, ()),
5960                config,
5961                pid: Pid::from_raw(child),
5962            };
5963            if committed {
5964                let target = guest.thread_state().dettid;
5965                crate::tool_global::child_exit_sigchld(
5966                    &mut guest,
5967                    ChildExitSigchldControl::PrivateSent { target },
5968                )
5969                .await;
5970            }
5971            let held = crate::syscalls::threads::futex_wait_held_after_wake(host_timed, 0);
5972            pending.push(
5973                crate::syscalls::threads::futex_wait_pending_signals(
5974                    &mut guest,
5975                    &state,
5976                    interrupting,
5977                    held,
5978                    host_timed,
5979                    0,
5980                )
5981                .await,
5982            );
5983        }
5984        owner.finish();
5985        assert_eq!(interrupting & chld, chld, "pending, unblocked and caught");
5986        assert_eq!(
5987            pending,
5988            vec![chld, 0, 0],
5989            "recorded, unrecorded, host-timed"
5990        );
5991    }
5992
5993    /// A futex wait's own check after a wake decides a held `SIGCHLD` from
5994    /// the private queue and the schedule's record together: after a flush
5995    /// cleared the record, a `SIGCHLD` only in the shared queue (which a
5996    /// host-timed source may have posted) ends nothing, and neither does a
5997    /// record whose copy is no longer in the private queue. Both waits park
5998    /// again (the design check of https://github.com/rrnewton/hermit/issues/4132).
5999    #[tokio::test(flavor = "current_thread")]
6000    async fn a_futex_waits_check_after_a_wake_needs_the_private_copy_and_its_record() {
6001        let chld = kernel_sigset_bit(libc::SIGCHLD);
6002        let state = |thread: KernelSigset, shared: KernelSigset| {
6003            crate::syscalls::threads::KernelSignalState {
6004                pending: thread | shared,
6005                thread_pending: thread,
6006                shared_pending: shared,
6007                caught: chld,
6008                ..Default::default()
6009            }
6010        };
6011        let mut answers = Vec::new();
6012        for (name, kernel, recorded, flushed) in [
6013            ("private, recorded", state(chld, 0), true, false),
6014            ("flushed, shared only", state(0, chld), true, true),
6015            ("recorded, shared only", state(0, chld), true, false),
6016        ] {
6017            let config = Config {
6018                sequentialize_threads: true,
6019                ..Config::default()
6020            }
6021            .with_backend(|backend| {
6022                backend.supports_blocked_wait_signal_interruption = true;
6023                backend.delivers_preemption_timer_events = false;
6024                backend.runs_guest_code_between_injections = false;
6025            });
6026            let global = GlobalState::for_tests(&config);
6027            let mut guest = SleeperGuest {
6028                state: &global,
6029                thread: ThreadState::new(DetPid::from_raw(4242), &config, ()),
6030                config,
6031                pid: Pid::from_raw(4242),
6032            };
6033            let target = guest.thread_state().dettid;
6034            if recorded {
6035                crate::tool_global::child_exit_sigchld(
6036                    &mut guest,
6037                    ChildExitSigchldControl::PrivateSent { target },
6038                )
6039                .await;
6040            }
6041            if flushed {
6042                crate::tool_global::child_exit_sigchld(
6043                    &mut guest,
6044                    ChildExitSigchldControl::Flushed,
6045                )
6046                .await;
6047            }
6048            let held = crate::syscalls::threads::futex_wait_held_after_wake(0, 0);
6049            let interrupting = kernel.pending_interrupting(kernel.blocked, false);
6050            let pending = crate::syscalls::threads::futex_wait_pending_signals(
6051                &mut guest,
6052                &kernel,
6053                interrupting,
6054                held,
6055                0,
6056                0,
6057            )
6058            .await;
6059            answers.push((name, pending));
6060        }
6061        assert_eq!(
6062            answers,
6063            vec![
6064                ("private, recorded", chld),
6065                ("flushed, shared only", 0),
6066                ("recorded, shared only", 0),
6067            ]
6068        );
6069    }
6070
6071    /// After the drain woke a futex waiter for a guest's private `SIGCHLD`,
6072    /// a sibling flushed it (`SIG_IGN`, then the handler again) and sent
6073    /// `kill(getpid(), SIGCHLD)`, a copy in the shared queue. Here a forked
6074    /// child, stopped with `SIGCHLD` caught and unblocked, is sent that shared
6075    /// copy, so `/proc` shows it in `ShdPnd` only, and the ledger records the
6076    /// private send and the flush. The waiter's check, as
6077    /// `handle_futex_blocking` runs it with the drain's `SIGCHLD` left out of
6078    /// the committed set (`drain_woken_waiters`), ends nothing, and the
6079    /// wait parks again: a futex wait holds shared copies. Had the drain's
6080    /// `SIGCHLD` been committed, as before the design check of
6081    /// https://github.com/rrnewton/hermit/issues/4132, the shared copy, which
6082    /// a host-timed child exit could equally have posted, would have ended it.
6083    #[tokio::test(flavor = "current_thread")]
6084    async fn a_shared_sigchld_after_a_flush_does_not_end_a_drain_woken_futex_wait() {
6085        let mut owner = forked_child(false);
6086        let child = owner.pid;
6087        if let Err(waited) = owner.wait_stopped() {
6088            panic!("the child did not stop: {waited:?}");
6089        }
6090        // SAFETY: the child is ours and stopped; SIGCHLD stays pending.
6091        assert_eq!(
6092            unsafe { libc::kill(child, libc::SIGCHLD) },
6093            0,
6094            "kill failed"
6095        );
6096        let state = crate::syscalls::threads::read_thread_wait_signal_state(
6097            Pid::from_raw(child),
6098            Pid::from_raw(child),
6099        )
6100        .expect("the child's signal state");
6101        let chld = kernel_sigset_bit(libc::SIGCHLD);
6102        let mut pending = Vec::new();
6103        for committed_wake in [0, chld] {
6104            let config = Config {
6105                sequentialize_threads: true,
6106                ..Config::default()
6107            }
6108            .with_backend(|backend| {
6109                backend.supports_blocked_wait_signal_interruption = true;
6110                backend.delivers_preemption_timer_events = false;
6111                backend.runs_guest_code_between_injections = false;
6112            });
6113            let global = GlobalState::for_tests(&config);
6114            let mut guest = SleeperGuest {
6115                state: &global,
6116                thread: ThreadState::new(DetPid::from_raw(child), &config, ()),
6117                config,
6118                pid: Pid::from_raw(child),
6119            };
6120            let target = guest.thread_state().dettid;
6121            crate::tool_global::child_exit_sigchld(
6122                &mut guest,
6123                ChildExitSigchldControl::PrivateSent { target },
6124            )
6125            .await;
6126            crate::tool_global::child_exit_sigchld(&mut guest, ChildExitSigchldControl::Flushed)
6127                .await;
6128            let held = crate::syscalls::threads::futex_wait_held_after_wake(0, committed_wake);
6129            pending.push(
6130                crate::syscalls::threads::futex_wait_pending_signals(
6131                    &mut guest,
6132                    &state,
6133                    state.pending_interrupting(state.blocked, false),
6134                    held,
6135                    0,
6136                    committed_wake,
6137                )
6138                .await,
6139            );
6140        }
6141        owner.finish();
6142        assert_eq!(
6143            (state.thread_pending & chld, state.shared_pending & chld),
6144            (0, chld),
6145            "SIGCHLD pending in the shared queue only"
6146        );
6147        assert_eq!(pending, vec![0, chld], "stripped, then committed as before");
6148    }
6149}
6150
6151#[cfg(test)]
6152mod own_process_signal_tests {
6153    use super::*;
6154
6155    const SENDER_SIBLING: i32 = 11;
6156
6157    /// The main thread sends SIGUSR1, which it catches, to its own process
6158    /// while one other thread is parked with an empty mask: admitted (S1).
6159    fn admitted_s1() -> OwnProcessSignal {
6160        OwnProcessSignal {
6161            sig: libc::SIGUSR1,
6162            names_sender: true,
6163            caught: kernel_sigset_bit(libc::SIGUSR1),
6164            inputs: OwnProcessSignalInputs {
6165                siblings: vec![(
6166                    DetTid::from_raw(SENDER_SIBLING),
6167                    SiblingSignalState::InSchedule(Some(0)),
6168                )],
6169                ..Default::default()
6170            },
6171            ..Default::default()
6172        }
6173    }
6174
6175    fn refusal(edit: impl FnOnce(&mut OwnProcessSignal)) -> Option<OwnProcessSignalRefusal> {
6176        let mut send = admitted_s1();
6177        edit(&mut send);
6178        own_process_signal_refusal(&send)
6179    }
6180
6181    /// The first byte user mode cannot read is found across contiguous
6182    /// readable, write-only and execute-only mappings, and is a `PROT_NONE`
6183    /// mapping, a hole, or a hole below a grow-down mapping.
6184    #[test]
6185    fn the_first_user_unreadable_byte_is_classified_by_its_mapping() {
6186        let smaps = "1000-2000 r--p 0 0:0 0\nVmFlags: rd mr\n\
6187                     2000-3000 -w-p 0 0:0 0\nVmFlags: wr mw\n\
6188                     3000-4000 ---p 0 0:0 0\nVmFlags: mr\n\
6189                     6000-7000 --xp 0 0:0 0 [vvar]\nVmFlags: ex\n\
6190                     9000-a000 rw-p 0 0:0 0 [stack]\nVmFlags: rd wr gd\n";
6191        let mappings = parse_smaps(smaps);
6192        assert_eq!(mappings.len(), 5);
6193        assert!(mappings[4].growsdown && !mappings[0].growsdown);
6194        assert_eq!(
6195            first_user_unreadable(&mappings, 0x1fc0, 128),
6196            None,
6197            "crosses from read-only into write-only"
6198        );
6199        assert_eq!(
6200            first_user_unreadable(&mappings, 0x6000, 128),
6201            None,
6202            "execute-only"
6203        );
6204        assert_eq!(
6205            first_user_unreadable(&mappings, 0x2fc0, 128),
6206            Some(Unreadable::NoPermission),
6207            "runs into PROT_NONE"
6208        );
6209        assert_eq!(
6210            first_user_unreadable(&mappings, 0x4000, 48),
6211            Some(Unreadable::Hole {
6212                below_growsdown: false
6213            }),
6214            "a hole below a fixed mapping"
6215        );
6216        assert_eq!(
6217            first_user_unreadable(&mappings, 0x8000, 48),
6218            Some(Unreadable::Hole {
6219                below_growsdown: true
6220            }),
6221            "a hole below the stack"
6222        );
6223        assert_eq!(
6224            first_user_unreadable(&mappings, 0xb000, 48),
6225            Some(Unreadable::Hole {
6226                below_growsdown: false
6227            }),
6228            "above every mapping"
6229        );
6230        assert_eq!(
6231            first_user_unreadable(&mappings, 0, 48),
6232            Some(Unreadable::Hole {
6233                below_growsdown: false
6234            })
6235        );
6236        assert_eq!(
6237            first_user_unreadable(&mappings, usize::MAX - 10, 48),
6238            Some(Unreadable::Hole {
6239                below_growsdown: false
6240            })
6241        );
6242    }
6243
6244    #[test]
6245    fn the_sender_named_by_its_call_is_admitted_whatever_its_siblings_masks() {
6246        assert_eq!(refusal(|_| {}), None);
6247    }
6248
6249    /// S2: the call names the leader but another thread sends; admitted only
6250    /// when every other live thread blocks the signal or has its exit granted.
6251    #[test]
6252    fn another_sender_is_admitted_only_when_every_live_sibling_blocks() {
6253        let usr1 = kernel_sigset_bit(libc::SIGUSR1);
6254        let leader = DetTid::from_raw(SENDER_SIBLING);
6255        assert_eq!(
6256            refusal(|send| send.names_sender = false),
6257            Some(OwnProcessSignalRefusal::NotSoleReceiver(leader))
6258        );
6259        assert_eq!(
6260            refusal(|send| {
6261                send.names_sender = false;
6262                send.inputs.siblings = vec![(leader, SiblingSignalState::InSchedule(Some(usr1)))];
6263            }),
6264            None
6265        );
6266        assert_eq!(
6267            refusal(|send| {
6268                send.names_sender = false;
6269                send.inputs.siblings = vec![(leader, SiblingSignalState::ExitGranted)];
6270            }),
6271            None
6272        );
6273    }
6274
6275    /// Only the seven admitted signals pass; each other signal is refused
6276    /// whatever its disposition.
6277    #[test]
6278    fn only_the_seven_signals_below_sigchld_are_admitted() {
6279        for sig in 1..=64 {
6280            let admitted = OWN_PROCESS_SIGNALS.contains(&sig);
6281            let got = refusal(|send| {
6282                send.sig = sig;
6283                send.caught = kernel_sigset_bit(sig);
6284            });
6285            if admitted {
6286                assert!(sig < libc::SIGCHLD, "signal {sig}");
6287                assert_eq!(got, None, "signal {sig}");
6288            } else {
6289                assert_eq!(
6290                    got,
6291                    Some(OwnProcessSignalRefusal::SignalNotAdmitted),
6292                    "signal {sig}"
6293                );
6294            }
6295        }
6296        for sig in [
6297            libc::SIGCHLD,
6298            libc::SIGCONT,
6299            libc::SIGTSTP,
6300            libc::SIGRTMIN(),
6301            libc::SIGSEGV,
6302            libc::SIGTRAP,
6303            libc::SIGSTKFLT,
6304            libc::SIGKILL,
6305            libc::SIGALRM,
6306        ] {
6307            assert!(!OWN_PROCESS_SIGNALS.contains(&sig), "signal {sig}");
6308        }
6309    }
6310
6311    #[test]
6312    fn a_default_disposition_is_refused_and_sig_ign_is_admitted() {
6313        assert_eq!(
6314            refusal(|send| send.caught = 0),
6315            Some(OwnProcessSignalRefusal::DefaultDisposition)
6316        );
6317        assert_eq!(
6318            refusal(|send| {
6319                send.caught = 0;
6320                send.ignored = kernel_sigset_bit(libc::SIGUSR1);
6321            }),
6322            None
6323        );
6324    }
6325
6326    #[test]
6327    fn each_mode_and_sender_state_refuses_by_name() {
6328        use OwnProcessSignalRefusal as R;
6329        let sibling = DetTid::from_raw(SENDER_SIBLING);
6330        assert_eq!(
6331            refusal(|send| send.record_replay = true),
6332            Some(R::RecordReplay)
6333        );
6334        assert_eq!(
6335            refusal(|send| send.schedule_replay = true),
6336            Some(R::ScheduleReplay)
6337        );
6338        assert_eq!(
6339            refusal(|send| send.inputs.guest_marker_signal = true),
6340            Some(R::GuestMarkerSignal)
6341        );
6342        assert_eq!(
6343            refusal(|send| send.stacktrace_signal = true),
6344            Some(R::StacktraceSignal)
6345        );
6346        assert_eq!(
6347            refusal(|send| send.blocked = kernel_sigset_bit(libc::SIGUSR1)),
6348            Some(R::SenderBlocks)
6349        );
6350        assert_eq!(
6351            refusal(|send| send.inputs.siblings[0].1 = SiblingSignalState::OutOfSchedule),
6352            Some(R::OutOfSchedule(sibling))
6353        );
6354        assert_eq!(
6355            refusal(|send| send.inputs.siblings[0].1 = SiblingSignalState::InSchedule(None)),
6356            Some(R::UnknownMask(sibling))
6357        );
6358        assert_eq!(
6359            refusal(|send| send.posthook_anchor = true),
6360            Some(R::PosthookAnchor)
6361        );
6362        assert_eq!(refusal(|send| send.signalfd = true), Some(R::Signalfd));
6363        assert_eq!(
6364            refusal(|send| send.inputs.exec_in_flight = true),
6365            Some(R::ExecInFlight)
6366        );
6367    }
6368
6369    /// The private queue refuses on any signal the sender does not block,
6370    /// except Reverie's timer marker.
6371    #[test]
6372    fn a_private_pending_signal_refuses_unless_blocked_or_the_timer_marker() {
6373        let hup = kernel_sigset_bit(libc::SIGHUP);
6374        let marker = kernel_sigset_bit(reverie::PERF_EVENT_SIGNAL as i32);
6375        assert_eq!(
6376            refusal(|send| send.thread_pending = hup),
6377            Some(OwnProcessSignalRefusal::PrivatePending(hup))
6378        );
6379        assert_eq!(
6380            refusal(|send| {
6381                send.thread_pending = hup;
6382                send.blocked = hup;
6383            }),
6384            None
6385        );
6386        assert_eq!(refusal(|send| send.thread_pending = marker), None);
6387    }
6388
6389    /// An armed host-timed source or a foreign exit signal refuses whatever its
6390    /// number, unless the sender blocks it.
6391    #[test]
6392    fn armed_sources_refuse_unless_the_sender_blocks_them() {
6393        let io = kernel_sigset_bit(libc::SIGIO);
6394        let usr2 = kernel_sigset_bit(libc::SIGUSR2);
6395        assert_eq!(
6396            refusal(|send| send.inputs.host_timed = io),
6397            Some(OwnProcessSignalRefusal::HostTimedSource(io))
6398        );
6399        assert_eq!(
6400            refusal(|send| {
6401                send.inputs.host_timed = io;
6402                send.blocked = io;
6403            }),
6404            None
6405        );
6406        assert_eq!(
6407            refusal(|send| send.inputs.foreign_exit_signals = usr2),
6408            Some(OwnProcessSignalRefusal::ForeignExitSignal(usr2))
6409        );
6410        assert_eq!(
6411            refusal(|send| {
6412                send.inputs.foreign_exit_signals = usr2;
6413                send.blocked = usr2;
6414            }),
6415            None
6416        );
6417    }
6418
6419    /// An undelivered scheduler signal refuses when numbered at or below the
6420    /// one sent, which it would precede or coalesce with, and not above it.
6421    #[test]
6422    fn an_undelivered_scheduler_signal_refuses_only_at_or_below_the_sent_one() {
6423        let term = libc::SIGTERM;
6424        for (pending, refuses) in [
6425            (libc::SIGHUP, true),
6426            (libc::SIGALRM, true),
6427            (libc::SIGTERM, true),
6428            (libc::SIGSTKFLT, false),
6429            (libc::SIGRTMIN(), false),
6430        ] {
6431            let bit = kernel_sigset_bit(pending);
6432            let got = refusal(|send| {
6433                send.sig = term;
6434                send.caught = kernel_sigset_bit(term);
6435                send.inputs.undelivered_scheduler_signals = bit;
6436            });
6437            assert_eq!(
6438                got,
6439                refuses.then_some(OwnProcessSignalRefusal::UndeliveredSchedulerSignal(bit)),
6440                "pending {pending}"
6441            );
6442        }
6443    }
6444}