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 arr) private static object GetTextContent(object ast) { + RuntimeHelpers.EnsureSufficientExecutionStack(); if (Truthy(Get(ast, "expr"))) ast = Get(ast, "expr"); if (!(ast is List list)) diff --git a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathInput.cs b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathInput.cs index 17090da..fbdd7a0 100644 --- a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathInput.cs +++ b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathInput.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 System.Text.RegularExpressions; using SharpEquations.Internal.Text; @@ -333,6 +334,7 @@ public static string MapFromPrivate(string s) /// astMapFromPrivate: over every string of a syntax tree. public static object AstMapFromPrivate(object ast) { + RuntimeHelpers.EnsureSufficientExecutionStack(); switch (ast) { case null: diff --git a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathPreprocess.cs b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathPreprocess.cs index 91fd200..e54fcb5 100644 --- a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathPreprocess.cs +++ b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathPreprocess.cs @@ -3,6 +3,7 @@ namespace SharpEquations.Internal.UnicodeMath using System; using System.Collections.Generic; using System.Linq; + using System.Runtime.CompilerServices; using static Js; using static UnicodeMathText; @@ -39,6 +40,7 @@ private sealed class PreprocessStyle private object Preprocess(PreprocessStyle dsty, object uast, int? index = null, List arr = null) { + RuntimeHelpers.EnsureSufficientExecutionStack(); bool intentSup = false; if (uast is List list) diff --git a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathPretty.cs b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathPretty.cs index 74c4a3f..eb14787 100644 --- a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathPretty.cs +++ b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathPretty.cs @@ -3,6 +3,7 @@ namespace SharpEquations.Internal.UnicodeMath using System; using System.Collections.Generic; using System.Linq; + using System.Runtime.CompilerServices; using System.Text; using static Js; using static UnicodeMathText; @@ -55,6 +56,7 @@ private static void PromoteAttributelessMrowChildren(List value) /// pretty: the MathML text of a MathML syntax tree. private string Pretty(object mast) { + RuntimeHelpers.EnsureSufficientExecutionStack(); if (mast is List list) { var sb = new StringBuilder(); diff --git a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathSerializer.cs b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathSerializer.cs index 5ca2731..a181c26 100644 --- a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathSerializer.cs +++ b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathSerializer.cs @@ -2,6 +2,7 @@ namespace SharpEquations.Internal.UnicodeMath { using System.Collections.Generic; using System.Linq; + using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Xml.Linq; using SharpEquations.Internal.Text; @@ -121,6 +122,7 @@ public static string Serialize(XElement math, bool keepSelectionInfo = false) /// internal static string Role(XElement e) { + RuntimeHelpers.EnsureSufficientExecutionStack(); var intent = Attr(e, "intent"); if (intent != null) return intent; @@ -210,6 +212,7 @@ private static bool IsHeld(XAttribute attribute) => private void FindLostIntents(XElement written, XElement read) { + RuntimeHelpers.EnsureSufficientExecutionStack(); if (Name(written) != Name(read)) { if (Name(written) == "mo" && Name(read) == "mi" && Text(written) == Text(read)) @@ -795,6 +798,7 @@ private string Nary(XElement node, string op, int cNode) private string Dump(XElement value, bool noAddParens = false) { + RuntimeHelpers.EnsureSufficientExecutionStack(); var ret = DumpCore(value, noAddParens); if (value == null || !explicitIntents.Contains(value) && !explicitArgs.Contains(value)) return ret; diff --git a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathTransform.cs b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathTransform.cs index 4045c88..1d5490d 100644 --- a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathTransform.cs +++ b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathTransform.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.RegularExpressions; using static Js; using static UnicodeMathText; @@ -139,6 +140,7 @@ private static string CheckCardinalityIntent(string intent, object miContent) /// mtransform: the MathML syntax tree of a preprocessed UnicodeMath syntax tree (dsty: bit 0 display, bit 1 right to left). private object Transform(int dsty, object puast) { + RuntimeHelpers.EnsureSufficientExecutionStack(); if (puast is List list && list.Count > 0) return TransformList(dsty, list); diff --git a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathTranslator.cs b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathTranslator.cs index 5db738b..5fb7dff 100644 --- a/src/SharpEquations/Internal/UnicodeMath/UnicodeMathTranslator.cs +++ b/src/SharpEquations/Internal/UnicodeMath/UnicodeMathTranslator.cs @@ -31,7 +31,7 @@ internal sealed partial class UnicodeMathTranslator /// public static string ToMathML(string unicodemath, bool display, bool alignmentMarks = false, bool strict = false, CancellationToken cancellationToken = default) { - return ToMathML(unicodemath, display, alignmentMarks, false, strict, cancellationToken); + return ToMathML(unicodemath, display, alignmentMarks, null, strict, cancellationToken); } /// @@ -71,11 +71,13 @@ public static string FromLaTeX(string tex, bool display, bool alignmentMarks = f display = true; unicodemath = string.Concat(umChars.Skip(1)); } - return ToMathML(unicodemath, display, alignmentMarks, true, strict, cancellationToken); + return ToMathML(unicodemath, display, alignmentMarks, tex, strict, cancellationToken); } - private static string ToMathML(string unicodemath, bool display, bool alignmentMarks, bool tex, bool strict, CancellationToken cancellationToken) + /// The LaTeX the UnicodeMath was read from, or null when it was given as UnicodeMath. + private static string ToMathML(string unicodemath, bool display, bool alignmentMarks, string latex, bool strict, CancellationToken cancellationToken) { + var tex = latex != null; unicodemath = unicodemath.Trim(); var resolved = UnicodeMathInput.ResolveControlWords(unicodemath, strict ? unknown => throw new FormatException("Unknown control word " + unknown + (tex ? " in the LaTeX." : ".")) @@ -87,7 +89,7 @@ private static string ToMathML(string unicodemath, bool display, bool alignmentM // a closing bracket that LaTeX leaves without its opening one (𝑣⌋𝐵, 𝑎)) is a character, which UnicodeMath escapes if (!UnicodeMathGrammar.TryParse(input, cancellationToken, out var uast) && !(tex && UnicodeMathGrammar.TryParse(UnicodeMathInput.MapToPrivate(UnicodeMathInput.SetBuilderBars(UnicodeMathInput.EscapeUnpairedClosers(resolved))), cancellationToken, out uast))) - throw new FormatException("Not valid UnicodeMath: " + unicodemath); + throw new FormatException(tex ? "Not valid LaTeX: " + latex : "Not valid UnicodeMath: " + unicodemath); uast = UnicodeMathInput.AstMapFromPrivate(uast); var translator = new UnicodeMathTranslator { alignmentMarks = alignmentMarks, FTeX = tex }; diff --git a/src/SharpEquations/Public/Equation.cs b/src/SharpEquations/Public/Equation.cs index 1bbda3d..446f5d9 100644 --- a/src/SharpEquations/Public/Equation.cs +++ b/src/SharpEquations/Public/Equation.cs @@ -142,6 +142,7 @@ public Equation WithDisplay(bool display) /// /// The equation as OMML: an m:oMathPara element for a display equation, an m:oMath one otherwise. /// + /// The equation is nested too deeply to be written on the stack of this thread. public XElement ToOmml() => (XElement)EquationSerializer.Serialize(mathML, EquationFormat.Omml, EquationOptions.Default); /// The equation in a format: MathML and OMML as XML text. @@ -152,6 +153,7 @@ public Equation WithDisplay(bool display) /// /// cannot be written. /// is not a format. + /// The equation is nested too deeply to be written on the stack of this thread. public string ToString(EquationFormat format, EquationOptions? options = null) { if (format == EquationFormat.MathML) diff --git a/src/SharpEquations/Public/EquationConverter.cs b/src/SharpEquations/Public/EquationConverter.cs index aa09413..b38023f 100644 --- a/src/SharpEquations/Public/EquationConverter.cs +++ b/src/SharpEquations/Public/EquationConverter.cs @@ -31,6 +31,7 @@ public static class EquationConverter /// is binary. /// A format is not a format. /// cannot be written. + /// The equation is nested too deeply to be written on the stack of this thread. /// is not a valid equation in . /// was cancelled. public static string Convert(string source, EquationFormat sourceFormat, EquationFormat destinationFormat, @@ -51,6 +52,7 @@ public static string Convert(string source, EquationFormat sourceFormat, Equatio /// is not an XML format. /// A format is not a format. /// cannot be written. + /// The equation is nested too deeply to be written on the stack of this thread. /// is not an equation in . public static string Convert(XElement source, EquationFormat sourceFormat, EquationFormat destinationFormat, EquationOptions? options = null) { @@ -68,6 +70,7 @@ public static string Convert(XElement source, EquationFormat sourceFormat, Equat /// is not a binary format. /// A format is not a format. /// cannot be written. + /// The equation is nested too deeply to be written on the stack of this thread. /// is not a supported MTEF equation. public static string Convert(ReadOnlySpan source, EquationFormat sourceFormat, EquationFormat destinationFormat, EquationOptions? options = null) { @@ -85,6 +88,7 @@ public static string Convert(ReadOnlySpan source, EquationFormat sourceFor /// is binary. /// A format is not a format. /// cannot be written. + /// The equation is nested too deeply to be written on the stack of this thread. public static bool TryConvert([NotNullWhen(true)] string? source, EquationFormat sourceFormat, EquationFormat destinationFormat, [NotNullWhen(true)] out string? result, EquationOptions? options = null) { diff --git a/tests/SharpEquations.Tests/Omml/OmmlTests.cs b/tests/SharpEquations.Tests/Omml/OmmlTests.cs index 63c50f6..3afd80b 100644 --- a/tests/SharpEquations.Tests/Omml/OmmlTests.cs +++ b/tests/SharpEquations.Tests/Omml/OmmlTests.cs @@ -375,7 +375,7 @@ public async Task RejectsDeeplyNestedEquations() var inner = new XElement(Mml + "mi", "x"); for (var i = 0; i < 2000; i++) inner = new XElement(Mml + "mrow", inner); - await Assert.That(() => OmmlSerializer.Serialize(new XElement(Mml + "math", inner))).ThrowsExactly(); + await Assert.That(() => OmmlSerializer.Serialize(new XElement(Mml + "math", inner))).ThrowsExactly(); } [Test] diff --git a/tests/SharpEquations.Tests/Property/FuzzTests.cs b/tests/SharpEquations.Tests/Property/FuzzTests.cs index eed6d4b..86865c3 100644 --- a/tests/SharpEquations.Tests/Property/FuzzTests.cs +++ b/tests/SharpEquations.Tests/Property/FuzzTests.cs @@ -243,8 +243,8 @@ public async Task RefusesMathMLNestedDeeperThanOmmlHolds() var math = new XElement(MathMLNamespaces.MathML + "mi", "x"); for (int i = 0; i < 2000; i++) math = new XElement(MathMLNamespaces.MathML + "msqrt", math); - var equation = Equation.Parse(new XElement(MathMLNamespaces.MathML + "math", math), EquationFormat.MathML); - await Assert.That(() => equation.ToOmml()).ThrowsException(); + await Assert.That(() => Equation.Parse(new XElement(MathMLNamespaces.MathML + "math", math), EquationFormat.MathML)) + .Throws(); } } } diff --git a/tests/SharpEquations.Tests/Regression/DeepNestingTests.cs b/tests/SharpEquations.Tests/Regression/DeepNestingTests.cs new file mode 100644 index 0000000..914dbe2 --- /dev/null +++ b/tests/SharpEquations.Tests/Regression/DeepNestingTests.cs @@ -0,0 +1,152 @@ +#nullable enable + +namespace SharpEquations.Tests.Regression +{ + using System; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using SharpEquations; + + /// + /// Equations nested deeply enough to overflow the stack, which ended the process (issue 69): they are rejected with + /// an exception that can be caught, on a thread with the 1 MB stack of Windows. + /// + public class DeepNestingTests + { + private const int Stack = 1024 * 1024; + + private static string Nest(string open, string inner, string close, int depth) => + string.Concat(Enumerable.Repeat(open, depth)) + inner + string.Concat(Enumerable.Repeat(close, depth)); + + private static Exception? OnThread(Action action) + { + Exception? thrown = null; + var thread = new Thread(() => + { + try + { + action(); + } + catch (Exception e) + { + thrown = e; + } + }, Stack); + thread.Start(); + thread.Join(); + return thrown; + } + + /// + /// The equations of the issue: near the limit, whether they are read or refused depends on the runtime and its + /// frames, but they never end the process. + /// + [Test] + [Arguments(@"\left(", "x", @"\right)", 300)] + [Arguments(@"\frac{1}{", "x", "}", 500)] + [Arguments(@"\sqrt{", "x", "}", 1000)] + [Arguments("x_{", "x", "}", 1000)] + [Arguments("{", "x", "}", 1200)] + [Arguments("", "x", "^x", 600)] + [Arguments("", "x", "^x", 800)] + [Arguments("", "x", "_x", 600)] + [Arguments("", "x", "_x", 800)] + [Arguments("", "x", @"\sqrt", 600)] + [Arguments("", "x", @"\sqrt", 800)] + public async Task ReadsOrRejectsTheEquationsOfTheIssue(string open, string inner, string close, int depth) + { + var latex = Nest(open, inner, close, depth); + foreach (var strict in new[] { false, true }) + { + var thrown = OnThread(() => Equation.Parse(latex, EquationFormat.LaTeX, new EquationOptions { Strict = strict }).ToOmml()); + if (thrown is not null and not FormatException) + await Assert.That(thrown).IsTypeOf(); + } + } + + [Test] + [Arguments(@"\left(", @"\right)", 5000)] + [Arguments(@"\frac{1}{", "}", 1000)] + [Arguments(@"\frac{1}{", "}", 5000)] + [Arguments(@"\sqrt{", "}", 1000)] + [Arguments("x_{", "}", 1000)] + [Arguments("{", "}", 5000)] + public async Task RejectsDeepLaTeX(string open, string close, int depth) + { + var latex = Nest(open, "x", close, depth); + var thrown = OnThread(() => Equation.Parse(latex, EquationFormat.LaTeX).ToOmml()); + await Assert.That(thrown).IsTypeOf(); + var parsed = true; + OnThread(() => parsed = Equation.TryParse(latex, EquationFormat.LaTeX, out _)); + await Assert.That(parsed).IsFalse(); + } + + [Test] + [Arguments("^x")] + [Arguments("_x")] + [Arguments(@"\sqrt")] + public async Task RejectsLongLaTeXChains(string link) + { + // no braces: the chain of scripts or commands nests what it builds + var latex = "x" + string.Concat(Enumerable.Repeat(link, 5000)); + var thrown = OnThread(() => Equation.Parse(latex, EquationFormat.LaTeX, new EquationOptions { Strict = true })); + await Assert.That(thrown).IsTypeOf(); + await Assert.That(thrown!.Message).DoesNotContain("UnicodeMath"); + } + + [Test] + [Arguments("(", ")", 5000)] + [Arguments("√(", ")", 5000)] + [Arguments("1/(", ")", 1000)] + [Arguments("x_(", ")", 5000)] + [Arguments("├(", "┤)", 5000)] + public async Task RejectsDeepUnicodeMath(string open, string close, int depth) + { + var thrown = OnThread(() => Equation.Parse(Nest(open, "x", close, depth), EquationFormat.UnicodeMath).ToOmml()); + await Assert.That(thrown).IsTypeOf(); + } + + [Test] + [Arguments("", "", 1000)] + [Arguments("1", "", 1000)] + [Arguments("", "", 20000)] + public async Task RejectsDeepMathML(string open, string close, int depth) + { + var mathML = "" + Nest(open, "x", close, depth) + ""; + var thrown = OnThread(() => Equation.Parse(mathML, EquationFormat.MathML)); + await Assert.That(thrown).IsTypeOf().And.HasMessageEqualTo("The equation is nested too deeply."); + } + + // two levels of XML for each: deeper than MaxDepth whatever the stack + [Test] + [Arguments("", "", 1000)] + [Arguments("", "", 20000)] + [Arguments("1", "", 400)] + [Arguments("", "", 400)] + [Arguments("x", "", 400)] + [Arguments("", "", 300)] + public async Task RejectsDeepOmml(string open, string close, int depth) + { + var omml = "" + + Nest(open, "x", close, depth) + ""; + var thrown = OnThread(() => Equation.Parse(omml, EquationFormat.Omml)); + await Assert.That(thrown).IsTypeOf().And.HasMessageEqualTo("The equation is nested too deeply."); + } + + [Test] + [Arguments(EquationFormat.MathML)] + [Arguments(EquationFormat.Omml)] + [Arguments(EquationFormat.UnicodeMath)] + [Arguments(EquationFormat.LaTeX)] + public async Task WritesOrRejectsDeepEquations(EquationFormat format) + { + // read within the limit, but deeper than some writers can recurse on a 1 MB stack + var mathML = "" + Nest("1", "x", "", 400) + ""; + var equation = Equation.Parse(mathML, EquationFormat.MathML); + var thrown = OnThread(() => equation.ToString(format)); + if (thrown is not null) + await Assert.That(thrown).IsTypeOf().And.HasMessageEqualTo("The equation is nested too deeply."); + } + } +}