diff --git a/AGENTS.md b/AGENTS.md
index 38999ac..c41d37d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -71,6 +71,11 @@ init-only record: `Display`, `Strict`, `PreserveFormatting`, `LaTeXFlavor` stand
- `EquationPipeline` picks the parser of a format by pattern matching on the format and the source;
`EquationSerializer` picks the serializer.
+- A stack overflow cannot be caught, and ends the process: the XML of a source and every equation read are refused
+ (`FormatException`, "The equation is nested too deeply.") beyond `EquationStylesheets.MaxDepth` levels, and every
+ method that recurses over an equation (the readers, the writers, the templates the XSLT generator compiles) starts
+ with `RuntimeHelpers.EnsureSufficientExecutionStack()`: its exception is a `FormatException` (`InvalidDataException`
+ for MTEF) when reading and an `InsufficientExecutionStackException` when writing. A new recursive method calls it too.
- `MathMLParser.Normalize` gives every equation the one form an `Equation` holds and compares: MathML namespace without
prefixes, no `mfenced`, `a` or invisible fences, no formatting unless kept, intents with plain letters, letters as
MathML Core writes them (`x` for an italic letter, `𝐲` rather than `mathvariant="bold"`, plain letters with
diff --git a/BuildVersion.props b/BuildVersion.props
index 01b17db..81d4215 100644
--- a/BuildVersion.props
+++ b/BuildVersion.props
@@ -2,7 +2,7 @@
- 1.1.1
+ 1.1.2
diff --git a/src/SharpEquations.XsltGenerator/StylesheetCompiler.cs b/src/SharpEquations.XsltGenerator/StylesheetCompiler.cs
index 605164e..3f035d6 100644
--- a/src/SharpEquations.XsltGenerator/StylesheetCompiler.cs
+++ b/src/SharpEquations.XsltGenerator/StylesheetCompiler.cs
@@ -305,6 +305,9 @@ private string Assemble()
// templates
+ // the templates recurse over the input, and a stack overflow cannot be caught
+ private const string EnsureStack = "System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack();";
+
private void CompileTemplate(XElement template, int index)
{
var name = Attr(template, "name", false);
@@ -319,6 +322,7 @@ private void CompileTemplate(XElement template, int index)
var signature = string.Concat(named.Parameters.Select((p, i) => ", object? a" + i));
var w = new CodeWriter(2);
w.Line().Open("private void " + named.Method + "(XObject n0, int p0, int s0" + signature + ")");
+ w.Line(EnsureStack);
CompileBody(template, parameters, i => "a" + i, w);
w.Close();
members.Append(w);
@@ -525,6 +529,7 @@ private void CompileDispatch(int mode)
w.Close();
w.Line().Open("private void Dispatch" + mode + "(XObject node, int position, int size, TemplateArguments? args)");
+ w.Line(EnsureStack);
w.Open("switch (node)");
w.Line("case XElement element:").Open();
diff --git a/src/SharpEquations/Internal/EquationPipeline.cs b/src/SharpEquations/Internal/EquationPipeline.cs
index c765aba..ad25dc8 100644
--- a/src/SharpEquations/Internal/EquationPipeline.cs
+++ b/src/SharpEquations/Internal/EquationPipeline.cs
@@ -38,10 +38,22 @@ public static XElement Read(object? source, EquationFormat format, EquationOptio
throw new ArgumentNullException(nameof(source));
CheckDefined(format);
cancellationToken.ThrowIfCancellationRequested();
+ try
+ {
+ return ReadSource(source, format, options, cancellationToken);
+ }
+ catch (InsufficientExecutionStackException e)
+ {
+ throw new FormatException(EquationStylesheets.TooDeep, e);
+ }
+ }
+
+ private static XElement ReadSource(object source, EquationFormat format, EquationOptions options, CancellationToken cancellationToken)
+ {
var math = (format, source) switch
{
- (EquationFormat.MathML, XElement element) => element,
- (EquationFormat.MathML, string text) => MathMLParser.ParseXml(text, format),
+ (EquationFormat.MathML, XElement element) => Shallow(element),
+ (EquationFormat.MathML, string text) => Shallow(MathMLParser.ParseXml(text, format)),
(EquationFormat.Omml, XElement element) => ReadOmml(element, options),
(EquationFormat.Omml, string text) => ReadOmml(MathMLParser.ParseXml(text, format), options),
(EquationFormat.UnicodeMath, string text) => UnicodeMathParser.Parse(text, options.Display, options.Strict, cancellationToken),
@@ -49,7 +61,7 @@ public static XElement Read(object? source, EquationFormat format, EquationOptio
(EquationFormat.Mtef, _) => throw new ArgumentException("MTEF equations are binary: pass them as bytes.", nameof(format)),
_ => throw new ArgumentException(format + " equations are text, not XML: pass them as strings.", nameof(format)),
};
- return MathMLParser.Normalize(math, options, format == EquationFormat.MathML);
+ return Shallow(MathMLParser.Normalize(math, options, format == EquationFormat.MathML));
}
/// Reads a binary source, MTEF, without copying it.
@@ -58,9 +70,26 @@ public static XElement Read(ReadOnlySpan source, EquationFormat format, Eq
CheckDefined(format);
if (format != EquationFormat.Mtef)
throw new ArgumentException(format + " equations are not binary: pass them as " + (IsXml(format) ? "text or XML." : "text."), nameof(format));
- return MathMLParser.Normalize(MtefParser.Parse(source), options, false);
+ try
+ {
+ var math = MathMLParser.Normalize(MtefParser.Parse(source), options, false);
+ if (EquationStylesheets.IsTooDeep(math))
+ throw new InvalidDataException("The MTEF equation is nested too deeply.");
+ return math;
+ }
+ catch (InsufficientExecutionStackException e)
+ {
+ throw new InvalidDataException("The MTEF equation is nested too deeply.", e);
+ }
}
+ ///
+ /// The equation, unless it is nested more deeply than : what reads and
+ /// writes it recurses over its tree, and a stack overflow cannot be caught.
+ ///
+ private static XElement Shallow(XElement math) =>
+ EquationStylesheets.IsTooDeep(math) ? throw new FormatException(EquationStylesheets.TooDeep) : math;
+
private static void CheckDefined(EquationFormat format)
{
if (!IsDefined(format))
@@ -69,6 +98,7 @@ private static void CheckDefined(EquationFormat format)
private static XElement ReadOmml(XElement omml, EquationOptions options)
{
+ Shallow(omml);
if (options.Strict)
OmmlParser.Validate(omml);
try
diff --git a/src/SharpEquations/Internal/EquationSerializer.cs b/src/SharpEquations/Internal/EquationSerializer.cs
index e499553..e2467d1 100644
--- a/src/SharpEquations/Internal/EquationSerializer.cs
+++ b/src/SharpEquations/Internal/EquationSerializer.cs
@@ -2,6 +2,7 @@
namespace SharpEquations.Internal
{
+ using System;
using System.Xml.Linq;
using SharpEquations.Internal.LaTeX;
using SharpEquations.Internal.MathML;
@@ -12,16 +13,25 @@ namespace SharpEquations.Internal
internal static class EquationSerializer
{
/// An XElement for the XML formats, a string for the others.
+ /// The equation is nested too deeply to be written on this thread.
public static object Serialize(XElement math, EquationFormat format, EquationOptions options)
{
EquationPipeline.CheckWritable(format);
- return format switch
+ try
{
- EquationFormat.MathML => MathMLSerializer.Serialize(math),
- EquationFormat.Omml => OmmlSerializer.Serialize(math),
- EquationFormat.UnicodeMath => UnicodeMathSerializer.Serialize(math),
- _ => LaTeXSerializer.Serialize(math, options.LaTeXFlavor == LaTeXFlavor.Standard),
- };
+ return format switch
+ {
+ EquationFormat.MathML => MathMLSerializer.Serialize(math),
+ EquationFormat.Omml => OmmlSerializer.Serialize(math),
+ EquationFormat.UnicodeMath => UnicodeMathSerializer.Serialize(math),
+ _ => LaTeXSerializer.Serialize(math, options.LaTeXFlavor == LaTeXFlavor.Standard),
+ };
+ }
+ catch (InsufficientExecutionStackException e) when (e.Message != EquationStylesheets.TooDeep)
+ {
+ // the writers recurse over the equation, and a stack overflow cannot be caught
+ throw new InsufficientExecutionStackException(EquationStylesheets.TooDeep, e);
+ }
}
public static string ToText(object serialized) =>
diff --git a/src/SharpEquations/Internal/EquationStylesheets.cs b/src/SharpEquations/Internal/EquationStylesheets.cs
index b93cec9..e7e3872 100644
--- a/src/SharpEquations/Internal/EquationStylesheets.cs
+++ b/src/SharpEquations/Internal/EquationStylesheets.cs
@@ -1,7 +1,6 @@
namespace SharpEquations.Internal
{
using System;
- using System.Collections.Generic;
using System.Xml.Linq;
using SharpEquations.Internal.Xslt;
@@ -16,12 +15,18 @@ internal static class EquationStylesheets
///
public const int MaxDepth = 512;
+ /// The message of the exceptions thrown for an equation nested more deeply than can be handled.
+ public const string TooDeep = "The equation is nested too deeply.";
+
+ /// Whether the element is nested more than levels deep.
+ public static bool IsTooDeep(XElement element) => Depth(element) > MaxDepth;
+
/// Runs the stylesheet, or returns null when its output is empty.
- /// The input is nested more than levels deep.
+ /// The input is nested more than levels deep.
public static XElement Transform(string name, XElement input)
{
- if (Depth(input) > MaxDepth)
- throw new ArgumentException("The equation is nested too deeply.", nameof(input));
+ if (IsTooDeep(input))
+ throw new InsufficientExecutionStackException(TooDeep);
switch (name)
{
case "omml2mml.xsl":
@@ -37,22 +42,43 @@ public static XElement Transform(string name, XElement input)
}
}
+ // without allocating: the input of every equation read goes through it (FirstNode would make an XText of
+ // the text of a token)
private static int Depth(XElement root)
{
- var depth = 0;
- var stack = new Stack<(XElement Element, int Depth)>();
- stack.Push((root, 1));
- while (stack.Count > 0)
+ int depth = 1, deepest = 1;
+ var element = root;
+ while (true)
{
- var (element, level) = stack.Pop();
- if (level > depth)
- depth = level;
- if (depth > MaxDepth)
- break;
- foreach (var child in element.Elements())
- stack.Push((child, level + 1));
+ var child = element.HasElements ? NextElement(element.FirstNode) : null;
+ if (child != null)
+ {
+ element = child;
+ if (++depth > deepest && (deepest = depth) > MaxDepth)
+ return deepest;
+ continue;
+ }
+ while (true)
+ {
+ if (element == root)
+ return deepest;
+ var sibling = NextElement(element.NextNode);
+ if (sibling != null)
+ {
+ element = sibling;
+ break;
+ }
+ element = element.Parent;
+ depth--;
+ }
}
- return depth;
+ }
+
+ private static XElement NextElement(XNode node)
+ {
+ while (node != null && node is not XElement)
+ node = node.NextNode;
+ return (XElement)node;
}
}
}
diff --git a/src/SharpEquations/Internal/LaTeX/LaTeXReader.cs b/src/SharpEquations/Internal/LaTeX/LaTeXReader.cs
index 0a5e4e0..6321edd 100644
--- a/src/SharpEquations/Internal/LaTeX/LaTeXReader.cs
+++ b/src/SharpEquations/Internal/LaTeX/LaTeXReader.cs
@@ -3,6 +3,7 @@ namespace SharpEquations.Internal.LaTeX
using System;
using System.Collections.Generic;
using System.Linq;
+ using System.Runtime.CompilerServices;
using System.Text;
using SharpEquations.Internal.UnicodeMath;
using static SharpEquations.Internal.UnicodeMath.UnicodeMathText;
@@ -484,6 +485,7 @@ private static bool AngleCloses(Text tex, int i)
///
private static string RewriteTeXOnly(string latex)
{
+ RuntimeHelpers.EnsureSufficientExecutionStack();
var tex = new Text(latex);
var result = new StringBuilder();
// between ⟨ and ⟩ a bar parts a bra from a ket (│), as in UnicodeMath: ⟨a│b⟩
@@ -2096,6 +2098,7 @@ private static (string, int) ApplyMacro(Text tex, int i, bool accentsAfter)
/// TeX2UMath: pass 2, LaTeX with UnicodeMath characters to UnicodeMath.
private string Pass2(string latex)
{
+ RuntimeHelpers.EnsureSufficientExecutionStack();
var tex = new Text(latex);
var uniTeX = new StringBuilder();
int j, k;
diff --git a/src/SharpEquations/Internal/LaTeX/LaTeXSerializer.cs b/src/SharpEquations/Internal/LaTeX/LaTeXSerializer.cs
index 3065e61..6aedb7f 100644
--- a/src/SharpEquations/Internal/LaTeX/LaTeXSerializer.cs
+++ b/src/SharpEquations/Internal/LaTeX/LaTeXSerializer.cs
@@ -3,6 +3,7 @@ namespace SharpEquations.Internal.LaTeX
using System;
using System.Collections.Generic;
using System.Linq;
+ using System.Runtime.CompilerServices;
using System.Xml.Linq;
using SharpEquations.Internal.UnicodeMath;
using static SharpEquations.Internal.UnicodeMath.Js;
@@ -229,6 +230,7 @@ private static string EquationNumber(string eq)
private string TeX(XElement value, bool noAddParens = false)
{
+ RuntimeHelpers.EnsureSufficientExecutionStack();
if (value == null)
return "";
diff --git a/src/SharpEquations/Internal/UnicodeMath/JsObject.cs b/src/SharpEquations/Internal/UnicodeMath/JsObject.cs
index 4e1a648..7c3944f 100644
--- a/src/SharpEquations/Internal/UnicodeMath/JsObject.cs
+++ b/src/SharpEquations/Internal/UnicodeMath/JsObject.cs
@@ -261,6 +261,7 @@ public static object V(object value)
public static object Clone(object value)
{
+ RuntimeHelpers.EnsureSufficientExecutionStack();
switch (value)
{
case JsObject o: return o.Clone();
@@ -276,6 +277,7 @@ public static object Clone(object value)
/// The string conversion of JavaScript (String(value)).
public static string Str(object value)
{
+ RuntimeHelpers.EnsureSufficientExecutionStack();
switch (value)
{
case null: return "undefined";
@@ -290,6 +292,7 @@ public static string Str(object value)
public static string Stringify(object value)
{
+ RuntimeHelpers.EnsureSufficientExecutionStack();
switch (value)
{
case null: return "null";
diff --git a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathHelpers.cs b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathHelpers.cs
index ec29292..bbd73fd 100644
--- a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathHelpers.cs
+++ b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathHelpers.cs
@@ -4,6 +4,7 @@ namespace SharpEquations.Internal.UnicodeMath
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+ using System.Runtime.CompilerServices;
using System.Text;
using static Js;
using static UnicodeMathText;
@@ -54,6 +55,7 @@ private static object DropSingletonLists(object uast)
private static object DropOutermostParens(object uast)
{
+ RuntimeHelpers.EnsureSufficientExecutionStack();
if (Truthy(Get(uast, "expr")))
return O("expr", DropOutermostParens(Get(uast, "expr")));
@@ -625,6 +627,7 @@ private static bool IsLeviCivita(object basE, object low, List