Skip to main content

einvoice_xpath_eval/
limit.rs

1//! Limits that keep the processing of a document within a bounded call stack.
2//!
3//! Walking a tree recursively needs stack in proportion to its depth: without a bound, a
4//! small document nested deeply enough would overflow the stack of its thread, which
5//! aborts the whole process. A parsed document is therefore refused when an element is
6//! nested deeper than a maximum depth ([`DEFAULT_MAX_DEPTH`] unless the caller sets
7//! another one), with a [`LimitExceeded::Depth`] error.
8//!
9//! Evaluating an expression recurses over its tree, whose depth is bounded by
10//! [`einvoice_xpath::MAX_DEPTH`]. A host that evaluates expressions inside a recursion of
11//! its own (the templates and functions of a stylesheet) bounds the stack of the whole
12//! with a [`StackLimit`] ([`DynamicContext::with_stack_limit`](crate::DynamicContext::with_stack_limit)):
13//! the evaluation then ends with a [`LimitExceeded::Stack`] error when it would use more.
14
15use std::fmt;
16
17/// The maximum element depth of a parsed document, unless the caller sets another one:
18/// the document element is at depth 1, its child elements at depth 2, and so on.
19///
20/// 256, the value of libxml2's `xmlParserMaxDepth` (without `XML_PARSE_HUGE`). libxml2
21/// compares it with the number of open ancestors of an element, so `xmllint` accepts 257
22/// nested elements and refuses 258 ("Excessive depth in document: 256").
23pub const DEFAULT_MAX_DEPTH: u32 = 256;
24
25/// A limit that a document or a transformation exceeded: the input is refused rather
26/// than processed with an unbounded call stack.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28#[non_exhaustive]
29pub enum LimitExceeded {
30    /// An element is nested deeper than `max` elements (the document element is at
31    /// depth 1); `line` and `column` (1-based) are the start of its start tag.
32    Depth {
33        /// The maximum depth.
34        max: u32,
35        /// The line of the element's start tag.
36        line: u32,
37        /// The column of the element's start tag, in characters.
38        column: u32,
39    },
40    /// Template rules, built-in template rules, named templates and stylesheet functions
41    /// are invoked one inside another more than `max` deep.
42    Nesting {
43        /// The maximum nesting.
44        max: u32,
45    },
46    /// The invocations in progress, and the expressions they evaluate, use more than `max`
47    /// bytes of the call stack, measured from the start of the transformation (a
48    /// [`StackLimit`]): a stylesheet whose templates or functions need more stack per
49    /// level than the nesting allows for.
50    Stack {
51        /// The maximum, in bytes.
52        max: u32,
53    },
54    /// A template ends with an `xsl:call-template`, which ends with another, and so on,
55    /// more than `max` times in a row: tail calls, which need no stack (Saxon runs them in
56    /// place, as the executor does), but would run for ever when the recursion does not
57    /// end.
58    TailCalls {
59        /// The maximum number of tail calls in a row.
60        max: u32,
61    },
62}
63
64/// A bound on the call stack: at most `max` bytes deeper than the position of the stack
65/// where it was taken ([`StackLimit::from_here`]). Stacks grow downwards on every
66/// supported target, the WebAssembly shadow stack included; the distance is taken
67/// either way.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub struct StackLimit {
70    base: usize,
71    max: u32,
72}
73
74impl StackLimit {
75    /// A bound of `max` bytes below the current position of the stack.
76    #[must_use]
77    #[inline(never)]
78    pub fn from_here(max: u32) -> Self {
79        Self {
80            base: stack_position(),
81            max,
82        }
83    }
84
85    /// The bound, in bytes.
86    #[must_use]
87    pub const fn max(self) -> u32 {
88        self.max
89    }
90
91    /// The stack used between the position where the bound was taken and here.
92    #[must_use]
93    pub fn used(self) -> usize {
94        self.base.abs_diff(stack_position())
95    }
96
97    /// [`LimitExceeded::Stack`] when the stack used is beyond the bound.
98    ///
99    /// # Errors
100    ///
101    /// The stack used is beyond the bound.
102    pub fn check(self) -> Result<(), LimitExceeded> {
103        if u32::try_from(self.used()).map_or(true, |used| used > self.max) {
104            Err(LimitExceeded::Stack { max: self.max })
105        } else {
106            Ok(())
107        }
108    }
109}
110
111/// The position of the call stack: the address of a local of this function.
112#[inline(never)]
113fn stack_position() -> usize {
114    let marker = 0_u8;
115    std::hint::black_box(std::ptr::addr_of!(marker)).addr()
116}
117
118impl LimitExceeded {
119    /// The limit's value (bytes for [`LimitExceeded::Stack`]).
120    #[must_use]
121    pub const fn max(self) -> u32 {
122        match self {
123            Self::Depth { max, .. }
124            | Self::Nesting { max }
125            | Self::Stack { max }
126            | Self::TailCalls { max } => max,
127        }
128    }
129}
130
131impl fmt::Display for LimitExceeded {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        match self {
134            Self::Depth { max, line, column } => write!(
135                f,
136                "{line}:{column}: element nested deeper than the maximum depth of {max}"
137            ),
138            Self::Nesting { max } => write!(
139                f,
140                "templates and functions invoked one inside another more than {max} deep"
141            ),
142            Self::Stack { max } => write!(
143                f,
144                "templates and functions invoked one inside another use more than {max} bytes of stack"
145            ),
146            Self::TailCalls { max } => write!(
147                f,
148                "templates ending with a call of another template more than {max} times in a row"
149            ),
150        }
151    }
152}