Skip to main content

flm_core/lang/
guard.rs

1//! This module provides the recursion guard of FLM, which reports an error for
2//! deeply nested content before the content overflows the stack, along with the
3//! worker threads on which every guarded operation runs.
4//!
5//! Parsing, traversing, rewriting and serializing a tree are recursive
6//! operations, so deeply nested content uses much stack. A stack overflow ends
7//! the process, and the program that embeds FLM cannot recover from it. To
8//! prevent the overflow, techy provides a *descent guard*: the guard measures
9//! the stack that a recursive operation has used since it started, and stops the
10//! operation when this amount exceeds a budget. The operation then reports an
11//! error, for instance [`NestingTooDeep`] (`flm.blocks.nesting-too-deep`) for a
12//! parse. See also [the recursion guard and worker
13//! threads](crate::guide::concepts_overview#the-recursion-guard-and-worker-threads).
14//!
15//! # Guarded construction
16//!
17//! techy's default budget is small, and the budget of a language or of a
18//! traversal can only be set when the language or the traversal is constructed.
19//! FLM therefore constructs every recursive operation with one of the following
20//! functions of this module, which install the guard:
21//!
22//! - [`language`], for parsing;
23//! - [`walker`], [`restager`] and [`recomposer`], for traversals of a tree;
24//! - [`serde_session`], for serialization.
25//!
26//! The limit is selected with the [`GuardPolicy`] argument that each function
27//! takes.
28//! [`GuardPolicy::StackBudget`] limits the stack use and is the policy for
29//! normal use. [`GuardPolicy::DepthLimit`] limits the number of nested descents
30//! and is used in tests only.
31//!
32//! # The worker-thread requirement
33//!
34//! The guard cannot ask the operating system how much stack a thread has.
35//! Whoever creates a thread for guarded operations therefore declares the
36//! thread's stack once, where the thread starts, with [`mark_worker_thread`]
37//! and a [`WorkerStack`]. A thread marked in this way is a *worker thread*.
38//! Every guarded operation must run on a worker thread.
39//!
40//! The declared stack has three parts, and each is stated by the party that
41//! knows it:
42//!
43//! - The *reserved share* is for what the host runs on the thread outside the
44//!   guarded operations, such as the stack of a JavaScript engine that a
45//!   handler runs on. The host states it, in bytes
46//!   ([`WorkerStack::with_reserved`]). If the host states none, the reserved
47//!   share is one quarter of the declared size ([`WorkerStack::new`]).
48//! - The *library's margin* is for the library's own work that the guard does
49//!   not measure: the work between two checks of the guard, and the report of a
50//!   refusal. The library states it, and takes it off in every case, so that
51//!   deep content is refused rather than overflowing the stack even with a
52//!   reserved share of zero.
53//! - The rest is for the guarded operations, which together use at most that
54//!   much, measured from the place where the thread was marked. Each guarded
55//!   operation therefore gets, as its budget, the stack that remains on the
56//!   thread when it starts, less the reserved share and the margin: an
57//!   operation started inside another one gets less than one started at the top
58//!   of the thread.
59//!
60//! On a thread that is not marked, a guarded operation gets techy's small
61//! default budget (250 KiB), which fits in the stack of an ordinary thread but
62//! refuses content that is only moderately nested.
63//!
64//! The entry points of the library meet this requirement for their callers. They
65//! run each guarded operation through [`on_worker_thread`], which runs the
66//! operation on the current thread if this thread is marked as a worker thread,
67//! and otherwise on a new thread of [`WORKER_STACK_SIZE`] bytes of stack, marked
68//! with this size and the default reserved share. The [parse functions](crate::lang::parse),
69//! the [rewrite passes](crate::lang::rewrites), the run of a plan
70//! ([`Run`](crate::core::run::Run)) and the emitters of the standard backends work
71//! in this way. A program that embeds FLM therefore does not need to create
72//! worker threads.
73//!
74//! If you construct a guarded operation with a function of this module, or if
75//! you call [`copy_run_into_value`](crate::lang::copy::copy_run_into_value), run
76//! the operation inside [`on_worker_thread`].
77//!
78//! # A host with one thread
79//!
80//! A program that cannot create threads, such as a WebAssembly module, marks
81//! its one thread itself: call [`mark_worker_thread`] once, with the stack of
82//! the thread, before the first call of the host into the library (where the
83//! thread starts, or at the entry of that first call). Marking the thread again
84//! at the entry of a later call is also allowed, and replaces the declaration.
85//! [`on_worker_thread`] then runs every operation in place, and no thread is
86//! created. The size declared is at most the stack that is really available
87//! below the place of the mark; a WebAssembly module states the size that it is
88//! linked with (the linker's `-z stack-size`), from the same number that the
89//! build script gives to the linker. The reserved share declared is what the
90//! host's extensions need on that stack, which the host measures in its
91//! engine; a host that runs no JavaScript extension can declare a reserved
92//! share of zero.
93//!
94//! On `wasm32`, the guard measures the addresses of local variables. These lie
95//! in the stack inside the module's linear memory, so the guard protects that
96//! stack. It does not see the call stack of the engine that runs the module, so
97//! the host chooses a stack small enough that the guard refuses deep content
98//! before the engine's call stack is used up, and verifies this in its engine.
99//! The host links the stack that the guarded work needs together with the
100//! reserved share that it declares.
101//!
102//! # Content that exceeds the limit
103//!
104//! When the guard stops an operation, the operation does not panic. It reports
105//! an error and produces no result. For instance, a parse returns
106//! [`FragmentError::NestingTooDeep`](crate::lang::FragmentError::NestingTooDeep),
107//! which contains the error [`NestingTooDeep`]. A rewrite pass records the same
108//! error, and the tree that the pass was rewriting is absent from the output of
109//! the run.
110
111use std::cell::Cell;
112use std::thread;
113
114use techy::core::Language;
115use techy::core::StdDescentGuardInit;
116use techy::error::DiagnosticInfo;
117use techy::recompose::TreeRecomposer;
118use techy::serialize::{SerdeSession, SerializableLang};
119use techy::transform::TreeRestager;
120use techy::visit::TreeWalker;
121
122use crate::lang::flm::Flm;
123
124/// The stack size of the threads that the library creates for guarded
125/// operations, in bytes (64 MiB).
126///
127/// [`run_with_worker_stack`] and the thread pool of the runner create their
128/// threads with this much stack, and mark them with this size and the default
129/// reserved share (see [the
130/// worker-thread requirement](self#the-worker-thread-requirement)).
131pub const WORKER_STACK_SIZE: usize = 64 * 1024 * 1024;
132
133/// The stack that the library keeps for its own work that the recursion guard
134/// does not measure, in bytes: the work between two checks of the guard, and
135/// the report of a refusal. Taken off every budget, whatever the reserved share.
136const LIBRARY_MARGIN: usize = 256 * 1024;
137
138/// A `WorkerStack` is what a worker thread declares about its stack: its size,
139/// and the reserved share of it that guarded operations leave unused, both in
140/// bytes.
141///
142/// The reserved share is for what the host runs on the thread outside the
143/// guarded operations, such as the stack of a JavaScript engine that a handler
144/// runs on. Pass the declaration to [`mark_worker_thread`]; [`worker_stack`]
145/// answers it back (see [the worker-thread
146/// requirement](self#the-worker-thread-requirement)).
147///
148/// No value is refused. A reserved share as large as the declared size leaves
149/// no budget to guarded operations, and the recursion guard then refuses all
150/// nesting.
151///
152/// ```
153/// use flm_core::lang::guard::WorkerStack;
154///
155/// let stack = WorkerStack::new(8 * 1024 * 1024).with_reserved(0);
156/// assert_eq!(stack.size(), 8 * 1024 * 1024);
157/// assert_eq!(stack.reserved(), 0);
158/// ```
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct WorkerStack {
161    size: usize,
162    reserved: usize,
163}
164
165impl WorkerStack {
166    /// Returns a stack of `size` bytes, with a reserved share of one quarter of
167    /// it.
168    pub const fn new(size: usize) -> WorkerStack {
169        WorkerStack { size, reserved: size / 4 }
170    }
171
172    /// Returns the same stack with a reserved share of `reserved` bytes.
173    pub const fn with_reserved(self, reserved: usize) -> WorkerStack {
174        WorkerStack { reserved, ..self }
175    }
176
177    /// Returns the declared size of the stack, in bytes.
178    pub const fn size(&self) -> usize {
179        self.size
180    }
181
182    /// Returns the reserved share of the stack, in bytes.
183    pub const fn reserved(&self) -> usize {
184        self.reserved
185    }
186}
187
188/// The stack that a worker thread declares, and the stack position where the
189/// thread was marked.
190#[derive(Debug, Clone, Copy)]
191struct DeclaredStack {
192    /// The declaration passed to [`mark_worker_thread`].
193    stack: WorkerStack,
194    /// The stack position recorded by [`mark_worker_thread`].
195    top: usize,
196}
197
198thread_local! {
199    /// The stack that the current thread declares; `None` on a thread that is
200    /// not marked as a worker thread.
201    static DECLARED_STACK: Cell<Option<DeclaredStack>> = const { Cell::new(None) };
202}
203
204/// Returns the address of a local of its own frame, as the current stack
205/// position. Never inlined, so that the local lies in a frame of its own below
206/// the caller's.
207#[inline(never)]
208fn stack_position() -> usize {
209    let marker = 0u8;
210    std::hint::black_box(&marker as *const u8 as usize)
211}
212
213/// Marks the current thread as a worker thread with the declared `stack`.
214/// [`on_worker_thread`] then runs guarded operations directly on this thread,
215/// and their budget is derived from `stack`.
216///
217/// The current stack position is recorded as the top of the thread's stack:
218/// guarded operations together use at most the declared size less the reserved
219/// share and the library's margin, measured from this place. Call this function
220/// where the thread starts, or at the entry of the host's call into the
221/// library, and never inside a guarded operation. The declared size must be at
222/// most the stack that is really available below that place, for instance the
223/// size given to `std::thread::Builder::stack_size`, to the corresponding
224/// setting of a thread pool, or to the linker of a WebAssembly module. With a
225/// larger value, a guarded operation can overflow the stack before the
226/// recursion guard stops it (see [the worker-thread
227/// requirement](self#the-worker-thread-requirement)). A small size, or a large
228/// reserved share, is safe: the guard then refuses content that is less deeply
229/// nested.
230///
231/// Marking a thread again replaces its declaration. [`run_with_worker_stack`]
232/// marks the thread that it creates, so you do not need to call this function
233/// on that thread.
234///
235/// ```
236/// use flm_core::lang::guard::{self, WorkerStack};
237///
238/// let stack = WorkerStack::new(16 * 1024 * 1024).with_reserved(4 * 1024 * 1024);
239/// let declared = std::thread::Builder::new()
240///     .stack_size(stack.size())
241///     .spawn(move || {
242///         guard::mark_worker_thread(stack);
243///         guard::worker_stack()
244///     })
245///     .unwrap()
246///     .join()
247///     .unwrap();
248/// assert_eq!(declared, Some(stack));
249/// ```
250pub fn mark_worker_thread(stack: WorkerStack) {
251    let top = stack_position();
252    DECLARED_STACK.with(|declared| declared.set(Some(DeclaredStack { stack, top })));
253}
254
255/// Returns the stack that the current thread declared with
256/// [`mark_worker_thread`], or `None` if the current thread is not marked as a
257/// worker thread.
258pub fn worker_stack() -> Option<WorkerStack> {
259    DECLARED_STACK.with(|declared| declared.get()).map(|declared| declared.stack)
260}
261
262/// Returns the stack, in bytes, that remains on the current thread for guarded
263/// operations: the declared size, less the stack used since the thread was
264/// marked, less the reserved share, less [`LIBRARY_MARGIN`], saturating at
265/// zero. Returns `None` if the current thread is not marked as a worker thread.
266///
267/// The distance between the two positions is taken as an absolute difference,
268/// so no direction of stack growth is assumed.
269pub(crate) fn stack_budget() -> Option<usize> {
270    let declared = DECLARED_STACK.with(|declared| declared.get())?;
271    let used = declared.top.abs_diff(stack_position());
272    Some(
273        declared
274            .stack
275            .size()
276            .saturating_sub(used)
277            .saturating_sub(declared.stack.reserved())
278            .saturating_sub(LIBRARY_MARGIN),
279    )
280}
281
282/// Returns the number of levels that a recursive walk started here may open
283/// when one level uses at most `level_stack` bytes of stack: [`stack_budget`]
284/// divided by `level_stack`, or zero if the current thread is not marked as a
285/// worker thread.
286///
287/// The emitters, which count their own levels rather than use the guard of
288/// techy, read their limit with it once, when a walk starts.
289pub(crate) fn levels_within_budget(level_stack: usize) -> usize {
290    stack_budget().map_or(0, |budget| budget / level_stack)
291}
292
293/// Runs `f` on a worker thread and returns its result.
294///
295/// If the current thread is marked as a worker thread ([`worker_stack`]
296/// answers a declaration), `f` runs on the current thread. Otherwise, `f` runs on a
297/// new thread created with [`run_with_worker_stack`].
298///
299/// The entry points of the library call this function before they run a
300/// guarded operation (see [the worker-thread
301/// requirement](self#the-worker-thread-requirement)). Call it yourself around a
302/// guarded operation that you construct with the functions of this module.
303///
304/// # Errors
305///
306/// Returns the error of the operating system if a new thread is needed and the
307/// operating system fails to create it. In this case, `f` does not run.
308///
309/// # Panics
310///
311/// A panic inside `f` propagates to the caller, on whichever thread `f` ran.
312pub fn on_worker_thread<T, F>(f: F) -> std::io::Result<T>
313where
314    T: Send,
315    F: FnOnce() -> T + Send,
316{
317    if worker_stack().is_some() {
318        Ok(f())
319    } else {
320        run_with_worker_stack(f)
321    }
322}
323
324/// The error that is reported when content is nested too deeply to be
325/// processed (`flm.blocks.nesting-too-deep`).
326///
327/// Reported by a parse and by the rewrite passes when the recursion guard stops
328/// them (see the [module documentation](self)).
329///
330/// A parse that reports this error returns no fragment. When a rewrite pass
331/// reports this error, the tree that the pass was rewriting is absent from the
332/// output of the run.
333#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
334#[diagnostic(
335    id = "flm.blocks.nesting-too-deep",
336    message = "Content too deeply nested: {detail}"
337)]
338pub struct NestingTooDeep {
339    /// techy's description of the limit that was reached.
340    pub detail: String,
341}
342
343/// A `GuardPolicy` is the kind of limit that the recursion guard sets on a
344/// guarded operation. The default policy,
345/// [`StackBudget`](GuardPolicy::StackBudget), is the policy for normal use.
346#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
347pub enum GuardPolicy {
348    /// Stops the operation once it has used the stack that remained for
349    /// guarded operations on its thread when it started (see [the
350    /// worker-thread requirement](self#the-worker-thread-requirement)).
351    #[default]
352    StackBudget,
353    /// Stops the operation when it would open more than the given number of
354    /// descents at the same time. A parse opens about two descents for each
355    /// level of nesting, and a traversal opens one descent for each level of the
356    /// tree.
357    ///
358    /// Use this policy in tests only. It stops an operation at the same input on
359    /// every platform and with every build profile, which a test needs. However,
360    /// the number of descents does not measure the stack that each level uses, so
361    /// this policy does not protect against a stack overflow.
362    DepthLimit(usize),
363}
364
365impl GuardPolicy {
366    /// Returns this policy as a [`StdDescentGuardInit`], the configuration of
367    /// the descent guard that techy's constructors take.
368    ///
369    /// For [`StackBudget`](GuardPolicy::StackBudget), the budget is resolved on
370    /// the thread that runs the operation, when the operation starts: it is the
371    /// stack that remains there for guarded operations, less techy's own
372    /// headroom, or techy's default budget on a thread that is not marked as a
373    /// worker thread (see [the worker-thread
374    /// requirement](self#the-worker-thread-requirement)).
375    pub fn init(self) -> StdDescentGuardInit {
376        match self {
377            GuardPolicy::StackBudget => StdDescentGuardInit::computed_stack_budget(stack_budget),
378            GuardPolicy::DepthLimit(levels) => StdDescentGuardInit::depth_limit(levels),
379        }
380    }
381}
382
383/// Returns `language` with a recursion guard that applies `policy` to every
384/// parse with this language.
385///
386/// [`build_language`](crate::lang::build_language) calls this function on the
387/// language that it builds.
388pub fn language(language: Language<Flm>, policy: GuardPolicy) -> Language<Flm> {
389    language.with_descent_guard_init(policy.init())
390}
391
392/// Returns a [`TreeWalker`] for `visitor`, with a recursion guard that applies
393/// `policy`.
394///
395/// A tree walker traverses a tree without changing it. Use this function in
396/// place of `TreeWalker::new`, which installs techy's small default budget.
397pub fn walker<V: ?Sized>(visitor: &mut V, policy: GuardPolicy) -> TreeWalker<'_, V> {
398    TreeWalker::new(visitor).with_descent_guard_init(policy.init())
399}
400
401/// Returns a [`TreeRestager`] for `visitor`, with a recursion guard that
402/// applies `policy`.
403///
404/// A tree restager traverses a tree and builds a new tree from it, with
405/// changes applied. Use this function in place of `TreeRestager::new`, which
406/// installs techy's small default budget.
407pub fn restager<V: ?Sized>(visitor: &mut V, policy: GuardPolicy) -> TreeRestager<'_, V> {
408    TreeRestager::new(visitor).with_descent_guard_init(policy.init())
409}
410
411/// Returns a [`TreeRecomposer`] for `recomposer`, with a recursion guard that
412/// applies `policy`.
413///
414/// A tree recomposer traverses a tree and combines it into one value, for
415/// instance a string of source text. Use this function in place of
416/// `TreeRecomposer::new`, which installs techy's small default budget.
417pub fn recomposer<R: ?Sized>(recomposer: &mut R, policy: GuardPolicy) -> TreeRecomposer<'_, R> {
418    TreeRecomposer::new(recomposer).with_descent_guard_init(policy.init())
419}
420
421/// Returns `session` with a recursion guard that applies `policy` when the
422/// session serializes or deserializes a tree.
423pub fn serde_session<L: SerializableLang>(
424    session: SerdeSession<L>,
425    policy: GuardPolicy,
426) -> SerdeSession<L> {
427    session.with_descent_guard_init(policy.init())
428}
429
430/// Runs `f` on a new worker thread and returns its result.
431///
432/// The new thread is created with [`WORKER_STACK_SIZE`] bytes of stack, and it
433/// is marked as a worker thread with this size and the default reserved share
434/// (`WorkerStack::new(WORKER_STACK_SIZE)`, [`mark_worker_thread`]) as its first
435/// action. This function always creates a thread. In most cases, prefer
436/// [`on_worker_thread`], which creates a thread only if the current thread is
437/// not a worker thread.
438///
439/// # Errors
440///
441/// Returns the error of the operating system if the operating system fails to
442/// create the thread. In this case, `f` does not run.
443///
444/// # Panics
445///
446/// A panic inside `f` is caught on the new thread and resumed on the calling
447/// thread. The caller therefore observes the panic as if `f` had run on the
448/// calling thread.
449pub fn run_with_worker_stack<T, F>(f: F) -> std::io::Result<T>
450where
451    T: Send,
452    F: FnOnce() -> T + Send,
453{
454    thread::scope(|scope| {
455        let handle = thread::Builder::new().stack_size(WORKER_STACK_SIZE).spawn_scoped(scope, || {
456            mark_worker_thread(WorkerStack::new(WORKER_STACK_SIZE));
457            f()
458        })?;
459        match handle.join() {
460            Ok(value) => Ok(value),
461            Err(payload) => std::panic::resume_unwind(payload),
462        }
463    })
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn a_worker_run_returns_its_value() {
472        assert_eq!(run_with_worker_stack(|| 41 + 1).unwrap(), 42);
473    }
474
475    #[test]
476    fn a_worker_run_is_marked_and_the_caller_is_not() {
477        assert_eq!(worker_stack(), None);
478        let declared = run_with_worker_stack(worker_stack).unwrap().unwrap();
479        assert_eq!(declared.size(), WORKER_STACK_SIZE);
480        assert_eq!(worker_stack(), None);
481    }
482
483    /// Marks the current thread with `stack` and answers what it declares and
484    /// its budget, on a thread of the library.
485    fn marked_with(stack: WorkerStack) -> (Option<WorkerStack>, usize) {
486        run_with_worker_stack(move || {
487            mark_worker_thread(stack);
488            (worker_stack(), stack_budget().unwrap())
489        })
490        .unwrap()
491    }
492
493    #[test]
494    fn a_thread_answers_the_declaration_that_it_made() {
495        let default = WorkerStack::new(WORKER_STACK_SIZE);
496        assert_eq!(marked_with(default).0, Some(default));
497        let given = WorkerStack::new(WORKER_STACK_SIZE).with_reserved(1024 * 1024);
498        let declared = marked_with(given).0.unwrap();
499        assert_eq!(declared, given);
500        assert_eq!(declared.size(), WORKER_STACK_SIZE);
501        assert_eq!(declared.reserved(), 1024 * 1024);
502    }
503
504    #[test]
505    fn a_larger_reserved_share_gives_a_smaller_budget() {
506        let small = marked_with(WorkerStack::new(WORKER_STACK_SIZE).with_reserved(1024 * 1024)).1;
507        let large =
508            marked_with(WorkerStack::new(WORKER_STACK_SIZE).with_reserved(16 * 1024 * 1024)).1;
509        assert!(large < small, "{large} is not below {small}");
510    }
511
512    #[test]
513    fn a_reserved_share_of_the_whole_size_leaves_no_budget() {
514        let whole = WorkerStack::new(WORKER_STACK_SIZE).with_reserved(WORKER_STACK_SIZE);
515        assert_eq!(marked_with(whole).1, 0);
516    }
517
518    #[test]
519    fn a_marked_thread_runs_the_closure_in_place() {
520        let outside = thread::current().id();
521        let (ran_on, spawned) = run_with_worker_stack(|| {
522            let inner = thread::current().id();
523            let ran_on = on_worker_thread(|| thread::current().id()).unwrap();
524            (ran_on == inner, inner != outside)
525        })
526        .unwrap();
527        assert!(ran_on);
528        assert!(spawned);
529    }
530
531    #[test]
532    fn a_thread_that_is_not_marked_has_no_budget() {
533        assert_eq!(stack_budget(), None);
534    }
535
536    /// Descends `levels` frames of about 1 KiB each, then answers the budget.
537    #[inline(never)]
538    fn budget_below(levels: usize) -> Option<usize> {
539        let frame = std::hint::black_box([0u8; 1024]);
540        if levels == 0 {
541            stack_budget()
542        } else {
543            let budget = budget_below(levels - 1);
544            std::hint::black_box(&frame);
545            budget
546        }
547    }
548
549    #[test]
550    fn an_operation_started_deeper_gets_a_smaller_budget() {
551        let (top, deep) =
552            run_with_worker_stack(|| (stack_budget().unwrap(), budget_below(64).unwrap())).unwrap();
553        assert!(deep < top, "{deep} is not below {top}");
554        assert!(top <= WORKER_STACK_SIZE);
555    }
556}