Search code examples
.netxsltstack-overflow

Stack Overflow problem transforming with a custom xslt


I've got a system that allows the user the option of providing their own XSLT to apply to some data that's been retrieved, as a means of specifying how that data should be presented. However, if the user includes code in the XSLT equivalent to:

<xsl:template match="/">
  <xsl:element name="data">
    <xsl:apply-templates select="." />
  </xsl:element>
</xsl:template>

this causes .NET to infinitely recurse trying to process it, and produces a stack overflow error. I need to be able to trap this before it crashes the app, as the data that's been retrieved is occasionally quite time-consuming to obtain, and the data is lost when this happens.

Is there any way of doing this? I know it's theoretically possible to identify any occurrences of xsl:apply-templates with "." in the select attribute, but this isn't the only way an infinite recursion could happen, I need a way of generically trapping it.


Solution

  • You're talking about the halting problem. It is undecidable: it is impossible to create an algorithm that can determine whether or not any program (or, in your case, any XSLT script) will halt or continue processing indefinitely for its possible inputs.

    Your best bet is to impose time and/or memory limits on the execution of user-provided XSLT scripts. That's how browsers typically handle out-of-control JavaScript, for example.

    The drawback is you'll occasionally determine that some legitimate scripts are taking too much time and/or memory, so you'll have to tune your limits carefully.