Skip to main content

kizz_threads/
overflow.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! Kizz's handler of stack overflows ("Kizz never panics").
6//!
7//! Kizz does not prevent a stack overflow, such as one in Starlark's garbage
8//! collector when a task program nests values too deeply. It catches the overflow
9//! instead and stops in a controlled way, where Rust's runtime would abort the
10//! process.
11//!
12//! * [`install`] sets up the calling thread, the main thread, and installs the handler
13//!   for `SIGSEGV` and `SIGBUS`, with `SA_SIGINFO` and `SA_ONSTACK`, after it has kept
14//!   the earlier action of each signal. It installs the handler for both signals or for
15//!   neither, and its error names the call that failed.
16//! * Setting up a thread gives it an alternate signal stack of its own, of 64 KiB plus
17//!   the kernel's `AT_MINSIGSTKSZ`, above an inaccessible guard page, and records the
18//!   guard region of its stack in a thread-local value of plain integers. Once the
19//!   handler is installed, [`crate::spawn`] and [`crate::spawn_scoped`] set up each
20//!   thread at the start of its work, and restore its earlier alternate stack and unmap
21//!   kizz's one when the work ends; the main thread keeps its own. A thread whose
22//!   alternate stack or guard region cannot be set up runs without them, silently.
23//! * [`note_task`] and [`note_lock`] keep the location of the task whose program kizz
24//!   evaluates and the path of the lock file that it holds in static buffers of atomic
25//!   bytes, guarded by a sequence counter, until the [`Note`] is dropped.
26//!
27//! The handler acts only on a signal that the kernel raised for a fault
28//! (`si_code` above 0), in the process that installed it, at an address in the
29//! guard region of the faulting thread. It then writes a fixed error to standard
30//! error, naming the noted task when there is one, deletes the noted lock file, and
31//! exits with the status that [`install`] was given. It makes only calls that are
32//! safe in a signal handler (signal-safety(7)): `write`, `unlink`, `_exit`,
33//! `sigaction` and `getpid`. It allocates nothing, takes no lock, starts nothing and
34//! never returns into the overflowed code.
35//!
36//! Any other fault goes to the action that was there before: the handler restores
37//! it with `sigaction`, keeping `errno`, and returns, so the fault repeats under
38//! `std`'s handler, which reports its own overflow or restores the default action. A
39//! real crash is never swallowed.
40//!
41//! In builds with `debug_assertions`, [`fault_outside_guards`] makes the calling
42//! thread fault outside every guard region, for the `kizz` binary's end-to-end test.
43
44use std::{
45    cell::Cell,
46    ffi::c_void,
47    fmt, io,
48    os::unix::ffi::OsStrExt as _,
49    path::Path,
50    ptr,
51    sync::{
52        OnceLock,
53        atomic::{AtomicBool, AtomicI32, AtomicU8, AtomicU64, AtomicUsize, Ordering, fence},
54    },
55};
56
57/// The size of kizz's alternate signal stack before the kernel's
58/// `AT_MINSIGSTKSZ` is added: room for the handler's buffers, many times over.
59const ALT_STACK_BASE: usize = 65_536;
60
61/// The most bytes of a task's location that a note keeps; a longer text is cut at
62/// a character boundary.
63const TASK_CAPACITY: usize = 1_024;
64
65/// The most bytes of a lock file's path that a note keeps; with the closing zero
66/// byte the path fills [`PATH_BUFFER`] bytes at most, and a longer path is not
67/// noted.
68const LOCK_CAPACITY: usize = 4_095;
69
70/// The size of the handler's copy of the lock file's path, the closing zero byte
71/// included.
72const PATH_BUFFER: usize = 4_096;
73
74/// The size of the handler's message buffer: the longest message, with a task
75/// location of [`TASK_CAPACITY`] bytes, fits in it.
76const MESSAGE_CAPACITY: usize = 1_280;
77
78/// How many calls of `write` the handler makes at most for its message, retrying
79/// a short or interrupted write.
80const WRITE_ATTEMPTS: u32 = 8;
81
82/// What the message starts with when a task is noted.
83const TASK_PREFIX: &[u8] = b"error: the program of task ";
84
85/// What the message ends with when a task is noted.
86const TASK_SUFFIX: &[u8] =
87    b" overflowed the stack, so kizz stopped; its values are probably nested too deeply\n";
88
89/// The message when no task is noted.
90const NO_TASK: &[u8] = b"error: kizz overflowed its stack and stopped\n";
91
92/// The location of the task whose program kizz evaluates, while it is noted.
93static TASK: Slot<TASK_CAPACITY> = Slot::new();
94
95/// The path of the lock file that kizz holds, while it is noted.
96static LOCK: Slot<LOCK_CAPACITY> = Slot::new();
97
98/// The identity of the next note; 0 is no note.
99static NEXT_NOTE: AtomicU64 = AtomicU64::new(1);
100
101/// Whether the handler is installed, so that new threads are set up.
102static INSTALLED: AtomicBool = AtomicBool::new(false);
103
104/// The process that installed the handler, which alone it acts in.
105static INSTALLER: AtomicI32 = AtomicI32::new(0);
106
107/// The status that the handler exits with.
108static STATUS: AtomicI32 = AtomicI32::new(2);
109
110/// The action of `SIGSEGV` before the handler, written before the handler is
111/// installed.
112static EARLIER_SEGV: OnceLock<libc::sigaction> = OnceLock::new();
113
114/// The action of `SIGBUS` before the handler, written before the handler is
115/// installed.
116static EARLIER_BUS: OnceLock<libc::sigaction> = OnceLock::new();
117
118thread_local! {
119    /// The guard region of the calling thread's stack, or [`Region::NONE`] when the
120    /// thread is not set up: plain integers with a `const` initializer and no
121    /// destructor, which the handler reads without allocation, lazy initialization
122    /// or a panic.
123    static REGION: Cell<Region> = const { Cell::new(Region::NONE) };
124}
125
126/// A range of addresses, from `start` up to but not including `end`.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128struct Region {
129    /// The first address of the region.
130    start: usize,
131    /// The first address after the region.
132    end: usize,
133}
134
135impl Region {
136    /// No region: it contains no address.
137    const NONE: Self = Self { start: 0, end: 0 };
138
139    /// Whether `address` lies in the region.
140    const fn contains(
141        self,
142        address: usize,
143    ) -> bool {
144        self.start <= address && address < self.end
145    }
146}
147
148/// The guard region of a stack whose lowest address is `lowest`, with a guard of
149/// `guard_size` bytes and pages of `page` bytes: from `lowest` minus the guard to
150/// `lowest` plus the guard, where the guard is the larger of `guard_size` and
151/// `page`, because the system may report the guard below or above `lowest`.
152/// `None` when the guard is empty or the arithmetic would overflow.
153fn guard_region(
154    lowest: usize,
155    guard_size: usize,
156    page: usize,
157) -> Option<Region> {
158    let guard = guard_size.max(page);
159    if guard == 0 {
160        return None;
161    }
162    Some(Region {
163        start: lowest.checked_sub(guard)?,
164        end: lowest.checked_add(guard)?,
165    })
166}
167
168/// The size of an alternate signal stack, [`ALT_STACK_BASE`] plus `minimum`, the
169/// kernel's `AT_MINSIGSTKSZ`, rounded up to whole pages of `page` bytes; `None`
170/// when `page` is 0 or the arithmetic would overflow.
171fn alt_stack_size(
172    page: usize,
173    minimum: usize,
174) -> Option<usize> {
175    ALT_STACK_BASE
176        .checked_add(minimum)?
177        .checked_next_multiple_of(page)
178}
179
180/// The longest start of `text` that holds at most `capacity` bytes and ends at a
181/// character boundary.
182fn cut(
183    text: &str,
184    capacity: usize,
185) -> &str {
186    (0..=capacity.min(text.len()))
187        .rev()
188        .find(|&end| text.is_char_boundary(end))
189        .and_then(|end| text.get(..end))
190        .unwrap_or_default()
191}
192
193/// Write the handler's message into `out` and return its length: the message that
194/// names `task` when it is a noted location, and the message without a task
195/// otherwise. A message longer than `out` is cut, which no noted task causes in a
196/// buffer of [`MESSAGE_CAPACITY`] bytes.
197fn compose(
198    task: Option<&[u8]>,
199    out: &mut [u8],
200) -> usize {
201    let parts: [&[u8]; 3] = match task {
202        Some(task) if !task.is_empty() => [TASK_PREFIX, task, TASK_SUFFIX],
203        _ => [NO_TASK, &[], &[]],
204    };
205    let mut length: usize = 0;
206    for (slot, byte) in out
207        .iter_mut()
208        .zip(parts.iter().flat_map(|part| part.iter()))
209    {
210        *slot = *byte;
211        length = length.saturating_add(1);
212    }
213    length
214}
215
216/// A static buffer that holds one note of at most `N` bytes, written by kizz's
217/// threads and read by the handler without a lock.
218///
219/// A writer makes the sequence counter odd, changes the bytes, the length and the
220/// owner, and makes it even again; writers wait for each other on the counter. A
221/// reader copies the note and uses the copy only when the counter was even and
222/// unchanged across the copy, so a copy that a write overlapped is no note.
223struct Slot<const N: usize> {
224    /// The sequence counter: odd while a writer changes the note.
225    seq: AtomicU64,
226    /// The length of the note, 0 when there is none.
227    len: AtomicUsize,
228    /// The identity of the note's [`Note`], 0 when there is none.
229    owner: AtomicU64,
230    /// The bytes of the note.
231    bytes: [AtomicU8; N],
232}
233
234impl<const N: usize> Slot<N> {
235    /// A slot that holds no note.
236    const fn new() -> Self {
237        Self {
238            seq: AtomicU64::new(0),
239            len: AtomicUsize::new(0),
240            owner: AtomicU64::new(0),
241            bytes: [const { AtomicU8::new(0) }; N],
242        }
243    }
244
245    /// Make the counter odd once no other writer holds it.
246    fn begin(&self) {
247        loop {
248            let seq = self.seq.load(Ordering::Relaxed);
249            if (seq & 1) == 0
250                && self
251                    .seq
252                    .compare_exchange_weak(
253                        seq,
254                        seq.wrapping_add(1),
255                        Ordering::Acquire,
256                        Ordering::Relaxed,
257                    )
258                    .is_ok()
259            {
260                break;
261            }
262            std::hint::spin_loop();
263        }
264        fence(Ordering::Release);
265    }
266
267    /// Make the counter even again.
268    fn end(&self) {
269        self.seq.fetch_add(1, Ordering::Release);
270    }
271
272    /// Replace the note with the first `N` bytes of `bytes`, and return the
273    /// identity of the new note.
274    fn write(
275        &self,
276        bytes: &[u8],
277    ) -> u64 {
278        let id = NEXT_NOTE.fetch_add(1, Ordering::Relaxed);
279        self.begin();
280        let mut length: usize = 0;
281        for (slot, byte) in self.bytes.iter().zip(bytes) {
282            slot.store(*byte, Ordering::Relaxed);
283            length = length.saturating_add(1);
284        }
285        self.len.store(length, Ordering::Relaxed);
286        self.owner.store(id, Ordering::Relaxed);
287        self.end();
288        id
289    }
290
291    /// Remove the note when it is still the one with the identity `id`, so that an
292    /// older note never removes a newer one.
293    fn clear(
294        &self,
295        id: u64,
296    ) {
297        self.begin();
298        if self.owner.load(Ordering::Relaxed) == id {
299            self.len.store(0, Ordering::Relaxed);
300            self.owner.store(0, Ordering::Relaxed);
301        }
302        self.end();
303    }
304
305    /// Copy the note into the start of `out`, calling `between` after the copy and
306    /// before the check, and return its length; `None` when there is no note, when
307    /// it does not fit in `out`, or when a write overlapped the copy.
308    ///
309    /// Only atomic loads and the copy into `out` happen here, so the handler can
310    /// call it.
311    fn read(
312        &self,
313        out: &mut [u8],
314        between: impl FnOnce(),
315    ) -> Option<usize> {
316        let before = self.seq.load(Ordering::Acquire);
317        if (before & 1) != 0 {
318            return None;
319        }
320        let length = self.len.load(Ordering::Relaxed);
321        for (slot, byte) in out.iter_mut().zip(&self.bytes).take(length) {
322            *slot = byte.load(Ordering::Relaxed);
323        }
324        between();
325        fence(Ordering::Acquire);
326        let after = self.seq.load(Ordering::Relaxed);
327        (after == before && length > 0 && length <= out.len()).then_some(length)
328    }
329}
330
331/// A note of [`note_task`] or [`note_lock`], kept until it is dropped.
332#[derive(Debug)]
333#[must_use = "the note is removed when it is dropped"]
334pub struct Note {
335    /// The identity of the note, 0 when nothing was noted.
336    id: u64,
337    /// Removes the note from its slot.
338    clear: fn(u64),
339}
340
341impl Drop for Note {
342    fn drop(&mut self) {
343        if self.id != 0 {
344            (self.clear)(self.id);
345        }
346    }
347}
348
349/// Remove the task note with the identity `id`.
350fn clear_task(id: u64) {
351    TASK.clear(id);
352}
353
354/// Remove the lock note with the identity `id`.
355fn clear_lock(id: u64) {
356    LOCK.clear(id);
357}
358
359/// Note `text`, the location of the task whose program kizz evaluates, such as
360/// `kizz.md:12 (Deep)`, so that the handler names it, until the note is dropped.
361/// A text longer than 1,024 bytes is cut at a character boundary.
362pub fn note_task(text: &str) -> Note {
363    Note {
364        id: TASK.write(cut(text, TASK_CAPACITY).as_bytes()),
365        clear: clear_task,
366    }
367}
368
369/// Note `path`, the lock file that kizz holds, so that the handler deletes it,
370/// until the note is dropped. A path longer than 4,095 bytes, or one that holds a
371/// zero byte, is not noted; the next build then takes the file over.
372pub fn note_lock(path: &Path) -> Note {
373    let bytes = path.as_os_str().as_bytes();
374    if bytes.is_empty() || bytes.len() > LOCK_CAPACITY || bytes.contains(&0) {
375        return Note {
376            id: 0,
377            clear: clear_lock,
378        };
379    }
380    Note {
381        id: LOCK.write(bytes),
382        clear: clear_lock,
383    }
384}
385
386/// Why [`install`] could not install the handler.
387#[derive(Debug)]
388pub struct InstallError {
389    /// The call that failed, such as `sigaltstack`.
390    call: &'static str,
391    /// The system's error.
392    error: io::Error,
393}
394
395impl InstallError {
396    /// The error of `call`, which set `errno`.
397    fn last(call: &'static str) -> Self {
398        Self {
399            call,
400            error: io::Error::last_os_error(),
401        }
402    }
403
404    /// The error of `call`, which returned the error number `code`.
405    fn code(
406        call: &'static str,
407        code: i32,
408    ) -> Self {
409        Self {
410            call,
411            error: io::Error::from_raw_os_error(code),
412        }
413    }
414
415    /// The error of `call`, which gave a value that cannot be used.
416    fn invalid(
417        call: &'static str,
418        what: &'static str,
419    ) -> Self {
420        Self {
421            call,
422            error: io::Error::new(io::ErrorKind::InvalidData, what),
423        }
424    }
425}
426
427impl fmt::Display for InstallError {
428    fn fmt(
429        &self,
430        formatter: &mut fmt::Formatter<'_>,
431    ) -> fmt::Result {
432        write!(formatter, "{} failed: {}", self.call, self.error)
433    }
434}
435
436// The message holds the system's error, so the error has no source of its own.
437impl std::error::Error for InstallError {}
438
439/// The size of a page, from `sysconf`.
440fn page_size() -> Result<usize, InstallError> {
441    // SAFETY: `sysconf` has no preconditions.
442    let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
443    usize::try_from(page)
444        .ok()
445        .filter(|&page| page > 0)
446        .ok_or_else(|| InstallError::invalid("sysconf", "no page size"))
447}
448
449/// The guard region of the calling thread's stack, from `pthread_getattr_np`,
450/// `pthread_attr_getstack` and `pthread_attr_getguardsize`.
451fn stack_region() -> Result<Region, InstallError> {
452    let page = page_size()?;
453    let mut attributes = std::mem::MaybeUninit::<libc::pthread_attr_t>::uninit();
454    // SAFETY: `attributes` is valid for writing, and `pthread_self` names the calling
455    // thread, which is alive.
456    let status = unsafe { libc::pthread_getattr_np(libc::pthread_self(), attributes.as_mut_ptr()) };
457    if status != 0 {
458        return Err(InstallError::code("pthread_getattr_np", status));
459    }
460    let mut lowest: *mut c_void = ptr::null_mut();
461    let mut size: usize = 0;
462    let mut guard: usize = 0;
463    // SAFETY: `pthread_getattr_np` initialized `attributes`, and the other pointers
464    // are valid for writing.
465    let stack =
466        unsafe { libc::pthread_attr_getstack(attributes.as_ptr(), &raw mut lowest, &raw mut size) };
467    // SAFETY: as above.
468    let guarded = unsafe { libc::pthread_attr_getguardsize(attributes.as_ptr(), &raw mut guard) };
469    // SAFETY: `attributes` was initialized by `pthread_getattr_np` and is destroyed
470    // once.
471    unsafe { libc::pthread_attr_destroy(attributes.as_mut_ptr()) };
472    if stack != 0 {
473        return Err(InstallError::code("pthread_attr_getstack", stack));
474    }
475    if guarded != 0 {
476        return Err(InstallError::code("pthread_attr_getguardsize", guarded));
477    }
478    guard_region(lowest.addr(), guard, page)
479        .ok_or_else(|| InstallError::invalid("pthread_attr_getstack", "the guard region overflows"))
480}
481
482/// Kizz's alternate signal stack of a thread, and the one that it replaced.
483struct AltStack {
484    /// The start of the mapping, its guard page.
485    base: *mut c_void,
486    /// The length of the mapping, the guard page included.
487    length: usize,
488    /// The thread's alternate stack before kizz's.
489    earlier: libc::stack_t,
490}
491
492impl AltStack {
493    /// Map an alternate signal stack above an inaccessible guard page and make it
494    /// the calling thread's, keeping the earlier one.
495    fn set_up() -> Result<Self, InstallError> {
496        let page = page_size()?;
497        // SAFETY: `getauxval` has no preconditions; it gives 0 for an unknown entry.
498        let minimum = unsafe { libc::getauxval(libc::AT_MINSIGSTKSZ) };
499        let size = alt_stack_size(page, usize::try_from(minimum).unwrap_or(0))
500            .ok_or_else(|| InstallError::invalid("getauxval", "the signal stack size overflows"))?;
501        let length = size
502            .checked_add(page)
503            .ok_or_else(|| InstallError::invalid("getauxval", "the signal stack size overflows"))?;
504        // SAFETY: an anonymous private mapping at an address of the kernel's choosing
505        // touches no existing memory.
506        let base = unsafe {
507            libc::mmap(
508                ptr::null_mut(),
509                length,
510                libc::PROT_READ | libc::PROT_WRITE,
511                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_STACK,
512                -1,
513                0,
514            )
515        };
516        if base == libc::MAP_FAILED {
517            return Err(InstallError::last("mmap"));
518        }
519        // SAFETY: the first page lies in the mapping just made, which nothing else uses.
520        if unsafe { libc::mprotect(base, page, libc::PROT_NONE) } != 0 {
521            let error = InstallError::last("mprotect");
522            // SAFETY: the mapping was made above, and nothing refers to it.
523            unsafe { libc::munmap(base, length) };
524            return Err(error);
525        }
526        let stack = libc::stack_t {
527            ss_sp: base.cast::<u8>().wrapping_add(page).cast(),
528            ss_flags: 0,
529            ss_size: size,
530        };
531        // SAFETY: a zeroed `stack_t` is valid, and `sigaltstack` overwrites it.
532        let mut earlier: libc::stack_t = unsafe { std::mem::zeroed() };
533        // SAFETY: `stack` describes the accessible part of the mapping, which stays
534        // mapped until `restore`, and `earlier` is valid for writing.
535        if unsafe { libc::sigaltstack(&raw const stack, &raw mut earlier) } != 0 {
536            let error = InstallError::last("sigaltstack");
537            // SAFETY: the mapping was made above, and the thread does not use it.
538            unsafe { libc::munmap(base, length) };
539            return Err(error);
540        }
541        Ok(Self {
542            base,
543            length,
544            earlier,
545        })
546    }
547
548    /// Give the calling thread its earlier alternate stack back and unmap kizz's;
549    /// when the earlier one cannot be restored, kizz's stays mapped, because the
550    /// thread still uses it.
551    fn restore(self) {
552        // SAFETY: `earlier` is what `sigaltstack` reported for this thread.
553        if unsafe { libc::sigaltstack(&raw const self.earlier, ptr::null_mut()) } == 0 {
554            // SAFETY: the thread no longer uses the mapping, which nothing else refers
555            // to.
556            unsafe { libc::munmap(self.base, self.length) };
557        }
558    }
559}
560
561/// What setting up a thread did, undone when the thread's work ends.
562pub(crate) struct ThreadGuard {
563    /// Kizz's alternate stack of the thread, when it has one.
564    stack: Option<AltStack>,
565    /// Whether the thread's guard region was recorded.
566    region: bool,
567}
568
569impl Drop for ThreadGuard {
570    fn drop(&mut self) {
571        if self.region {
572            let _cleared: Result<(), std::thread::AccessError> =
573                REGION.try_with(|region| region.set(Region::NONE));
574        }
575        if let Some(stack) = self.stack.take() {
576            stack.restore();
577        }
578    }
579}
580
581/// Set up the calling thread, a thread that [`crate::spawn`] or
582/// [`crate::spawn_scoped`] started, once the handler is installed: give it kizz's
583/// alternate stack and record its guard region, each when it can be done. Nothing
584/// happens when the handler is not installed.
585pub(crate) fn guard_thread() -> ThreadGuard {
586    if !INSTALLED.load(Ordering::Acquire) {
587        return ThreadGuard {
588            stack: None,
589            region: false,
590        };
591    }
592    let region =
593        stack_region().is_ok_and(|region| REGION.try_with(|cell| cell.set(region)).is_ok());
594    ThreadGuard {
595        stack: AltStack::set_up().ok(),
596        region,
597    }
598}
599
600/// The earlier action of `signal`, when it was kept.
601fn earlier(signal: libc::c_int) -> Option<&'static libc::sigaction> {
602    match signal {
603        libc::SIGSEGV => EARLIER_SEGV.get(),
604        libc::SIGBUS => EARLIER_BUS.get(),
605        _ => None,
606    }
607}
608
609/// An action with every field zero: the default action, with an empty mask.
610fn zeroed_action() -> libc::sigaction {
611    // SAFETY: every field of `sigaction` is an integer, an integer array or an
612    // optional function pointer, for which zero is a valid value.
613    unsafe { std::mem::zeroed() }
614}
615
616/// Keep the current action of `signal` in `kept`, then install the handler for it.
617fn take_over(
618    signal: libc::c_int,
619    kept: &OnceLock<libc::sigaction>,
620) -> Result<(), InstallError> {
621    let mut current = zeroed_action();
622    // SAFETY: a null new action only reads the current one into `current`.
623    if unsafe { libc::sigaction(signal, ptr::null(), &raw mut current) } != 0 {
624        return Err(InstallError::last("sigaction"));
625    }
626    let _kept: &libc::sigaction = kept.get_or_init(|| current);
627    let mut action = zeroed_action();
628    let handler: extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut c_void) = handle;
629    action.sa_sigaction = handler as libc::sighandler_t;
630    action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK;
631    // SAFETY: `sa_mask` is a valid `sigset_t` to empty.
632    unsafe { libc::sigemptyset(&raw mut action.sa_mask) };
633    // SAFETY: `action` is a complete action whose handler has the `SA_SIGINFO`
634    // signature.
635    if unsafe { libc::sigaction(signal, &raw const action, ptr::null_mut()) } != 0 {
636        return Err(InstallError::last("sigaction"));
637    }
638    Ok(())
639}
640
641/// Give `signal` its kept earlier action back, or the default action when none was
642/// kept.
643fn give_back(signal: libc::c_int) {
644    let fallback = zeroed_action();
645    let action = earlier(signal).unwrap_or(&fallback);
646    // SAFETY: `action` is an action that `sigaction` reported, or the default action.
647    unsafe { libc::sigaction(signal, ptr::from_ref(action), ptr::null_mut()) };
648}
649
650/// Install kizz's handler of stack overflows for the process, which exits with
651/// `status` after an overflow, and set up the calling thread, which must be the main
652/// thread, first. The main thread keeps its alternate stack.
653///
654/// A second call does nothing.
655///
656/// # Errors
657///
658/// An [`InstallError`] that names the call that failed and the system's error,
659/// after the parts that succeeded are undone, so the handler is installed for both
660/// signals or for neither.
661pub fn install(status: u8) -> Result<(), InstallError> {
662    if INSTALLED.load(Ordering::Acquire) {
663        return Ok(());
664    }
665    let region = stack_region()?;
666    let stack = AltStack::set_up()?;
667    if REGION.try_with(|cell| cell.set(region)).is_err() {
668        stack.restore();
669        return Err(InstallError::invalid(
670            "thread_local",
671            "the thread is ending",
672        ));
673    }
674    STATUS.store(i32::from(status), Ordering::Relaxed);
675    // SAFETY: `getpid` has no preconditions and cannot fail.
676    INSTALLER.store(unsafe { libc::getpid() }, Ordering::Relaxed);
677    let undo = |stack: AltStack| {
678        let _cleared: Result<(), std::thread::AccessError> =
679            REGION.try_with(|cell| cell.set(Region::NONE));
680        stack.restore();
681    };
682    if let Err(error) = take_over(libc::SIGSEGV, &EARLIER_SEGV) {
683        undo(stack);
684        return Err(error);
685    }
686    if let Err(error) = take_over(libc::SIGBUS, &EARLIER_BUS) {
687        give_back(libc::SIGSEGV);
688        undo(stack);
689        return Err(error);
690    }
691    INSTALLED.store(true, Ordering::Release);
692    Ok(())
693}
694
695/// The handler of `SIGSEGV` and `SIGBUS`: stop kizz after an overflow of the
696/// faulting thread's stack, and hand every other fault to the earlier action.
697extern "C" fn handle(
698    signal: libc::c_int,
699    info: *mut libc::siginfo_t,
700    _context: *mut c_void,
701) {
702    if overflowed(info) {
703        stop();
704    }
705    // SAFETY: `__errno_location` gives the calling thread's `errno`, which is valid
706    // for the thread's life.
707    let errno = unsafe { *libc::__errno_location() };
708    give_back(signal);
709    // SAFETY: as above.
710    unsafe { *libc::__errno_location() = errno };
711}
712
713/// Whether `info` reports a fault that the kernel raised, in the process that
714/// installed the handler, at an address in the calling thread's guard region.
715fn overflowed(info: *const libc::siginfo_t) -> bool {
716    if info.is_null() {
717        return false;
718    }
719    // SAFETY: the kernel passes a valid `siginfo_t` to an `SA_SIGINFO` handler, and
720    // `si_addr` is the faulting address of `SIGSEGV` and `SIGBUS`.
721    let (code, address) = unsafe { ((*info).si_code, (*info).si_addr().addr()) };
722    if code <= 0 {
723        return false;
724    }
725    // SAFETY: `getpid` has no preconditions, and signal-safety(7) lists it.
726    if unsafe { libc::getpid() } != INSTALLER.load(Ordering::Relaxed) {
727        return false;
728    }
729    REGION
730        .try_with(Cell::get)
731        .is_ok_and(|region| region.contains(address))
732}
733
734/// Write the message, delete the noted lock file, and exit, with only `write`,
735/// `unlink` and `_exit`.
736#[inline(never)]
737fn stop() -> ! {
738    let mut task = [0_u8; TASK_CAPACITY];
739    let noted = TASK.read(&mut task, || {});
740    let mut message = [0_u8; MESSAGE_CAPACITY];
741    let length = compose(noted.and_then(|length| task.get(..length)), &mut message);
742    write_error(message.get(..length).unwrap_or_default());
743    let mut path = [0_u8; PATH_BUFFER];
744    let locked = path
745        .get_mut(..LOCK_CAPACITY)
746        .and_then(|start| LOCK.read(start, || {}));
747    if locked.is_some() {
748        // SAFETY: `path` holds the noted path and, after at most `LOCK_CAPACITY`
749        // bytes, a zero byte, because the buffer is one byte longer and starts zeroed.
750        unsafe { libc::unlink(path.as_ptr().cast()) };
751    }
752    // SAFETY: `_exit` ends the process at once, without running anything else.
753    unsafe { libc::_exit(STATUS.load(Ordering::Relaxed)) }
754}
755
756/// Write `bytes` to standard error with `write`, retrying a short or interrupted
757/// write at most [`WRITE_ATTEMPTS`] times in all, and dropping a write that fails.
758fn write_error(bytes: &[u8]) {
759    let mut rest = bytes;
760    for _attempt in 0..WRITE_ATTEMPTS {
761        if rest.is_empty() {
762            return;
763        }
764        // SAFETY: the pointer and length describe `rest`, which outlives the call.
765        let written = unsafe { libc::write(libc::STDERR_FILENO, rest.as_ptr().cast(), rest.len()) };
766        let Ok(count) = usize::try_from(written) else {
767            // SAFETY: as in `handle`.
768            if unsafe { *libc::__errno_location() } == libc::EINTR {
769                continue;
770            }
771            return;
772        };
773        if count == 0 {
774            return;
775        }
776        rest = rest.get(count..).unwrap_or_default();
777    }
778}
779
780/// Fault outside every guard region, by reading a page that is mapped without
781/// access, so that the end-to-end test sees the handler hand the fault on; only in
782/// builds with `debug_assertions`, which tests use and release builds lack. It
783/// returns only when the page cannot be mapped.
784#[cfg(debug_assertions)]
785pub fn fault_outside_guards() {
786    let Ok(page) = page_size() else {
787        return;
788    };
789    // SAFETY: an anonymous private mapping at an address of the kernel's choosing
790    // touches no existing memory.
791    let mapped = unsafe {
792        libc::mmap(
793            ptr::null_mut(),
794            page,
795            libc::PROT_NONE,
796            libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
797            -1,
798            0,
799        )
800    };
801    if mapped == libc::MAP_FAILED {
802        return;
803    }
804    // SAFETY: the read faults on purpose: the page has no access, so the kernel raises
805    // `SIGSEGV` before any value is read, and the fault ends the process.
806    let _byte: u8 = unsafe { ptr::read_volatile(mapped.cast::<u8>()) };
807    // SAFETY: the mapping was made above, and nothing refers to it.
808    unsafe { libc::munmap(mapped, page) };
809}
810
811/// Unit tests of the guard region, the notes and the messages.
812#[cfg(test)]
813#[allow(
814    clippy::arithmetic_side_effects,
815    clippy::disallowed_macros,
816    clippy::disallowed_methods,
817    reason = "test code: the tests assert, compute expected sizes and repeat text"
818)]
819mod tests {
820    use std::path::PathBuf;
821
822    use super::{
823        LOCK, LOCK_CAPACITY, MESSAGE_CAPACITY, NO_TASK, PATH_BUFFER, Region, Slot, TASK,
824        TASK_CAPACITY, TASK_PREFIX, TASK_SUFFIX, alt_stack_size, compose, cut, guard_region,
825        note_lock, note_task,
826    };
827
828    /// The size of a page in the tests of the guard region.
829    const PAGE: usize = 4_096;
830
831    /// The region runs from the lowest address minus the guard up to, not including,
832    /// the lowest address plus the guard, with its first and last addresses inside
833    /// and the first ones outside it outside.
834    #[test]
835    fn the_guard_region_surrounds_the_lowest_address() {
836        let region = guard_region(0x10_0000, PAGE, PAGE).unwrap();
837        assert_eq!(region, Region {
838            start: 0x10_0000 - PAGE,
839            end: 0x10_0000 + PAGE,
840        });
841        assert!(region.contains(0x10_0000 - PAGE));
842        assert!(region.contains(0x10_0000));
843        assert!(region.contains(0x10_0000 + PAGE - 1));
844        assert!(!region.contains(0x10_0000 - PAGE - 1));
845        assert!(!region.contains(0x10_0000 + PAGE));
846    }
847
848    /// The guard is the larger of the guard size and the page size, so a guard size
849    /// of zero gives a page, and a page size of zero with it gives no region.
850    #[test]
851    fn the_guard_is_at_least_a_page() {
852        assert_eq!(
853            guard_region(0x10_0000, 0, PAGE),
854            guard_region(0x10_0000, PAGE, PAGE)
855        );
856        assert_eq!(guard_region(0x10_0000, 4 * PAGE, PAGE).unwrap(), Region {
857            start: 0x10_0000 - 4 * PAGE,
858            end: 0x10_0000 + 4 * PAGE,
859        });
860        assert_eq!(guard_region(0x10_0000, 0, 0), None);
861    }
862
863    /// Addresses and sizes near 0 and `usize::MAX` give no region where the
864    /// arithmetic would overflow, and an exact region otherwise.
865    #[test]
866    fn the_guard_region_never_overflows() {
867        assert_eq!(guard_region(PAGE - 1, PAGE, PAGE), None);
868        assert_eq!(guard_region(0, PAGE, PAGE), None);
869        let low = guard_region(PAGE, PAGE, PAGE).unwrap();
870        assert!(low.contains(0));
871        assert!(!low.contains(2 * PAGE));
872        assert_eq!(guard_region(usize::MAX - PAGE + 1, PAGE, PAGE), None);
873        assert_eq!(guard_region(usize::MAX, 0, PAGE), None);
874        assert_eq!(guard_region(0x10_0000, usize::MAX, PAGE), None);
875        let high = guard_region(usize::MAX - PAGE, PAGE, PAGE).unwrap();
876        assert!(high.contains(usize::MAX - 1));
877        assert!(!high.contains(usize::MAX));
878        assert!(!Region::NONE.contains(0));
879        assert!(!Region::NONE.contains(usize::MAX));
880    }
881
882    /// The alternate stack holds 64 KiB plus the kernel's minimum, in whole pages,
883    /// and a size that would overflow, or a page size of zero, gives none.
884    #[test]
885    fn the_alternate_stack_is_whole_pages() {
886        assert_eq!(alt_stack_size(PAGE, 0), Some(65_536));
887        assert_eq!(alt_stack_size(PAGE, 3_000), Some(65_536 + 4_096));
888        assert_eq!(alt_stack_size(PAGE, PAGE), Some(65_536 + 4_096));
889        assert_eq!(alt_stack_size(0, 0), None);
890        assert_eq!(alt_stack_size(PAGE, usize::MAX), None);
891        assert_eq!(alt_stack_size(PAGE, usize::MAX - 65_536), None);
892    }
893
894    /// A note is read back as written, and dropping it removes it; a long task text
895    /// is cut at a character boundary, and a long path is not noted. The globals are
896    /// used by this one test only.
897    #[test]
898    fn notes_are_read_back_until_dropped() {
899        let mut out = [0_u8; TASK_CAPACITY];
900        let task = note_task("kizz.md:12 (Deep)");
901        assert_eq!(TASK.read(&mut out, || {}), Some(17));
902        assert_eq!(out.get(..17).unwrap(), b"kizz.md:12 (Deep)");
903        drop(task);
904        assert_eq!(TASK.read(&mut out, || {}), None);
905
906        let long = format!("{}é", "a".repeat(TASK_CAPACITY - 1));
907        let task = note_task(&long);
908        assert_eq!(TASK.read(&mut out, || {}), Some(TASK_CAPACITY - 1));
909        assert!(
910            out.get(..TASK_CAPACITY - 1)
911                .unwrap()
912                .iter()
913                .all(|&byte| byte == b'a')
914        );
915        drop(task);
916
917        let mut path = [0_u8; PATH_BUFFER];
918        let lock = note_lock(&PathBuf::from("/tmp/cache/kizz.lock"));
919        let start = path.get_mut(..LOCK_CAPACITY).unwrap();
920        assert_eq!(LOCK.read(start, || {}), Some(20));
921        assert_eq!(path.get(..21).unwrap(), b"/tmp/cache/kizz.lock\0");
922        drop(lock);
923        assert_eq!(LOCK.read(&mut path, || {}), None);
924
925        let longest = PathBuf::from(format!("/{}", "p".repeat(LOCK_CAPACITY - 1)));
926        let lock = note_lock(&longest);
927        assert_eq!(LOCK.read(&mut path, || {}), Some(LOCK_CAPACITY));
928        drop(lock);
929        let too_long = PathBuf::from(format!("/{}", "p".repeat(LOCK_CAPACITY)));
930        let lock = note_lock(&too_long);
931        assert_eq!(LOCK.read(&mut path, || {}), None);
932        drop(lock);
933        assert_eq!(PATH_BUFFER, LOCK_CAPACITY + 1);
934    }
935
936    /// A long text is cut at the last character boundary within the capacity.
937    #[test]
938    fn long_texts_are_cut_at_a_character_boundary() {
939        assert_eq!(cut("kizz.md:1", 100), "kizz.md:1");
940        assert_eq!(cut("abc", 2), "ab");
941        assert_eq!(cut("aé", 2), "a");
942        assert_eq!(cut("aé", 3), "aé");
943        assert_eq!(cut("é", 1), "");
944        assert_eq!(cut("", 0), "");
945    }
946
947    /// A copy that a write overlapped is no note, and the next copy reads the new
948    /// note.
949    #[test]
950    fn an_overlapped_copy_is_no_note() {
951        let slot: Slot<16> = Slot::new();
952        let mut out = [0_u8; 16];
953        let _first = slot.write(b"first");
954        assert_eq!(
955            slot.read(&mut out, || {
956                slot.write(b"second");
957            }),
958            None
959        );
960        assert_eq!(slot.read(&mut out, || {}), Some(6));
961        assert_eq!(out.get(..6).unwrap(), b"second");
962    }
963
964    /// An older note's removal leaves a newer note in place, and a note that does not
965    /// fit the reader's buffer is no note.
966    #[test]
967    fn only_the_current_note_is_removed() {
968        let slot: Slot<16> = Slot::new();
969        let mut out = [0_u8; 16];
970        let older = slot.write(b"older");
971        let newer = slot.write(b"newer");
972        slot.clear(older);
973        assert_eq!(slot.read(&mut out, || {}), Some(5));
974        let mut short = [0_u8; 3];
975        assert_eq!(slot.read(&mut short, || {}), None);
976        slot.clear(newer);
977        assert_eq!(slot.read(&mut out, || {}), None);
978        let empty = slot.write(b"");
979        assert_eq!(slot.read(&mut out, || {}), None);
980        slot.clear(empty);
981    }
982
983    /// Both messages, byte for byte, and the longest one fits the handler's buffer.
984    #[test]
985    fn the_messages_are_exact() {
986        let mut out = [0_u8; MESSAGE_CAPACITY];
987        let length = compose(Some(b"kizz.md:12 (Deep)".as_slice()), &mut out);
988        assert_eq!(
989            out.get(..length).unwrap(),
990            b"error: the program of task kizz.md:12 (Deep) overflowed the stack, so kizz stopped; \
991              its values are probably nested too deeply\n"
992        );
993        let length = compose(None, &mut out);
994        assert_eq!(
995            out.get(..length).unwrap(),
996            b"error: kizz overflowed its stack and stopped\n"
997        );
998        assert_eq!(compose(Some(b"".as_slice()), &mut out), NO_TASK.len());
999        let longest = [b'x'; TASK_CAPACITY];
1000        let length = compose(Some(longest.as_slice()), &mut out);
1001        assert_eq!(
1002            length,
1003            TASK_PREFIX.len() + TASK_CAPACITY + TASK_SUFFIX.len()
1004        );
1005        assert!(length <= MESSAGE_CAPACITY);
1006        assert!(out.get(..length).unwrap().ends_with(TASK_SUFFIX));
1007    }
1008}