如何防止和/或处理StackOverflowException?

时间:2008-10-15 22:47:24

标签: c# .net stack-overflow xslcompiledtransform

我想要阻止或处理我在StackOverflowException内写XslCompiledTransform.Transform方法时遇到的Xsl Editor。问题似乎是用户可以编写一个无限递归的Xsl script,它只会在调用Transform方法时爆炸。 (也就是说,问题不仅仅是典型的程序错误,这通常是造成这种异常的原因。)

有没有办法检测和/或限制允许的递归次数?还是有任何其他想法让这些代码不再让我感到震惊?

10 个答案:

答案 0 :(得分:59)

来自Microsoft:

  

从.NET Framework开始   版本2.0,StackOverflowException   try-catch无法捕获对象   块和相应的过程是   默认终止。所以,   建议用户编写代码   检测和防止堆栈   溢出。例如,如果你的   应用程序取决于递归,使用   反击或国家条件   终止递归循环。

我假设异常发生在内部.NET方法中,而不是在您的代码中。

你可以做几件事。

  • 编写检查xsl无限递归的代码,并在应用转换(Ugh)之前通知用户。
  • 将XslTransform代码加载到一个单独的进程中(Hacky,但工作量较少)。

您可以使用Process类加载将转换应用到单独进程的程序集,并在用户死亡时向用户发出故障警报,而不会终止主应用程序。

编辑:我刚刚测试过,这是怎么做的:

MainProcess:

// This is just an example, obviously you'll want to pass args to this.
Process p1 = new Process();
p1.StartInfo.FileName = "ApplyTransform.exe";
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

p1.Start();
p1.WaitForExit();

if (p1.ExitCode == 1)    
   Console.WriteLine("StackOverflow was thrown");

ApplyTransform Process:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        throw new StackOverflowException();
    }

    // We trap this, we can't save the process, 
    // but we can prevent the "ILLEGAL OPERATION" window 
    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        if (e.IsTerminating)
        {
            Environment.Exit(1);
        }
    }
}

答案 1 :(得分:22)

  

注意 @WilliamJockusch的赏金问题与原始问题不同。

     

这个答案是关于第三方库的一般情况下的StackOverflow以及您可以/不能使用它们的内容。如果您正在查看XslTransform的特殊情况,请参阅接受的答案。

堆栈溢出的发生是因为堆栈上的数据超过了某个限制(以字节为单位)。有关此检测工作原理的详细信息,请参见here

  

我想知道是否有一种跟踪StackOverflowExceptions的通用方法。换句话说,假设我的代码中某处有无限递归,但我不知道在哪里。我希望通过一些方法来跟踪它,这比在整个地方逐步执行代码更容易,直到我看到它发生。我不在乎它是多么的黑暗。

正如我在链接中提到的,检测静态代码分析中的堆栈溢出需要解决不可判定的暂停问题。既然我们已经确定没有银弹,我可以向您展示一些我认为有助于追踪问题的技巧。

我认为这个问题可以用不同的方式解释,因为我有点无聊:-),我会把它分解成不同的变体。

检测测试环境中的堆栈溢出

这里的问题基本上是你有一个(有限的)测试环境,并希望在(扩展的)生产环境中检测堆栈溢出。

我没有检测SO本身,而是通过利用可以设置堆栈深度的事实来解决这个问题。调试器将为您提供所需的所有信息。大多数语言允许您指定堆栈大小或最大递归深度。

基本上我尝试通过使堆栈深度尽可能小来强制SO。如果它没有溢出,我总是可以让生产环境更大(在这种情况下:更安全)。当您收到堆栈溢出的那一刻,您可以手动确定它是否有效'一个与否。

为此,将堆栈大小(在我们的例子中:一个小值)传递给Thread参数,看看会发生什么。 .NET中的默认堆栈大小为1 MB,我们将使用更小的值:

class StackOverflowDetector
{
    static int Recur()
    {
        int variable = 1;
        return variable + Recur();
    }

    static void Start()
    {
        int depth = 1 + Recur();
    }

    static void Main(string[] args)
    {
        Thread t = new Thread(Start, 1);
        t.Start();
        t.Join();
        Console.WriteLine();
        Console.ReadLine();
    }
}

注意:我们也会在下面使用此代码。

一旦溢出,你可以将它设置为更大的值,直到你得到一个有意义的SO。

在您之前创建例外

StackOverflowException无法捕获。这意味着当事情发生时,你无能为力。因此,如果您认为代码中的某些内容肯定会出错,那么在某些情况下您可以自己做出异常。你唯一需要的是当前的堆栈深度;如果没有计数器,您可以使用.NET中的实际值:

class StackOverflowDetector
{
    static void CheckStackDepth()
    {
        if (new StackTrace().FrameCount > 10) // some arbitrary limit
        {
            throw new StackOverflowException("Bad thread.");
        }
    }

    static int Recur()
    {
        CheckStackDepth();
        int variable = 1;
        return variable + Recur();
    }

    static void Main(string[] args)
    {
        try
        {
            int depth = 1 + Recur();
        }
        catch (ThreadAbortException e)
        {
            Console.WriteLine("We've been a {0}", e.ExceptionState);
        }
        Console.WriteLine();
        Console.ReadLine();
    }
}

请注意,如果您正在处理使用回调机制的第三方组件,则此方法也适用。唯一需要的是你可以拦截堆栈跟踪中的一些调用。

在单独的帖子中进行检测

你明确地建议了这一点,所以这就是这个。

您可以尝试在单独的线程中检测SO ..但它可能不会对您有任何好处。即使在进行上下文切换之前,堆栈溢出也可能发生 fast 。这意味着这种机制根本不可靠...... 我不建议实际使用它。虽然构建很有趣,所以这里的代码是: - )

class StackOverflowDetector
{
    static int Recur()
    {
        Thread.Sleep(1); // simulate that we're actually doing something :-)
        int variable = 1;
        return variable + Recur();
    }

    static void Start()
    {
        try
        {
            int depth = 1 + Recur();
        }
        catch (ThreadAbortException e)
        {
            Console.WriteLine("We've been a {0}", e.ExceptionState);
        }
    }

    static void Main(string[] args)
    {
        // Prepare the execution thread
        Thread t = new Thread(Start);
        t.Priority = ThreadPriority.Lowest;

        // Create the watch thread
        Thread watcher = new Thread(Watcher);
        watcher.Priority = ThreadPriority.Highest;
        watcher.Start(t);

        // Start the execution thread
        t.Start();
        t.Join();

        watcher.Abort();
        Console.WriteLine();
        Console.ReadLine();
    }

    private static void Watcher(object o)
    {
        Thread towatch = (Thread)o;

        while (true)
        {
            if (towatch.ThreadState == System.Threading.ThreadState.Running)
            {
                towatch.Suspend();
                var frames = new System.Diagnostics.StackTrace(towatch, false);
                if (frames.FrameCount > 20)
                {
                    towatch.Resume();
                    towatch.Abort("Bad bad thread!");
                }
                else
                {
                    towatch.Resume();
                }
            }
        }
    }
}

在调试器中运行它,并了解会发生什么。

使用堆栈溢出的特征

您的问题的另一种解释是:"可能导致堆栈溢出异常的代码段在哪里?"。显然,答案是:所有带递归的代码。对于每段代码,您可以进行一些手动分析。

使用静态代码分析也可以确定这一点。你需要做的是反编译所有方法并确定它们是否包含无限递归。以下是为您执行此操作的一些代码:

// A simple decompiler that extracts all method tokens (that is: call, callvirt, newobj in IL)
internal class Decompiler
{
    private Decompiler() { }

    static Decompiler()
    {
        singleByteOpcodes = new OpCode[0x100];
        multiByteOpcodes = new OpCode[0x100];
        FieldInfo[] infoArray1 = typeof(OpCodes).GetFields();
        for (int num1 = 0; num1 < infoArray1.Length; num1++)
        {
            FieldInfo info1 = infoArray1[num1];
            if (info1.FieldType == typeof(OpCode))
            {
                OpCode code1 = (OpCode)info1.GetValue(null);
                ushort num2 = (ushort)code1.Value;
                if (num2 < 0x100)
                {
                    singleByteOpcodes[(int)num2] = code1;
                }
                else
                {
                    if ((num2 & 0xff00) != 0xfe00)
                    {
                        throw new Exception("Invalid opcode: " + num2.ToString());
                    }
                    multiByteOpcodes[num2 & 0xff] = code1;
                }
            }
        }
    }

    private static OpCode[] singleByteOpcodes;
    private static OpCode[] multiByteOpcodes;

    public static MethodBase[] Decompile(MethodBase mi, byte[] ildata)
    {
        HashSet<MethodBase> result = new HashSet<MethodBase>();

        Module module = mi.Module;

        int position = 0;
        while (position < ildata.Length)
        {
            OpCode code = OpCodes.Nop;

            ushort b = ildata[position++];
            if (b != 0xfe)
            {
                code = singleByteOpcodes[b];
            }
            else
            {
                b = ildata[position++];
                code = multiByteOpcodes[b];
                b |= (ushort)(0xfe00);
            }

            switch (code.OperandType)
            {
                case OperandType.InlineNone:
                    break;
                case OperandType.ShortInlineBrTarget:
                case OperandType.ShortInlineI:
                case OperandType.ShortInlineVar:
                    position += 1;
                    break;
                case OperandType.InlineVar:
                    position += 2;
                    break;
                case OperandType.InlineBrTarget:
                case OperandType.InlineField:
                case OperandType.InlineI:
                case OperandType.InlineSig:
                case OperandType.InlineString:
                case OperandType.InlineTok:
                case OperandType.InlineType:
                case OperandType.ShortInlineR:
                    position += 4;
                    break;
                case OperandType.InlineR:
                case OperandType.InlineI8:
                    position += 8;
                    break;
                case OperandType.InlineSwitch:
                    int count = BitConverter.ToInt32(ildata, position);
                    position += count * 4 + 4;
                    break;

                case OperandType.InlineMethod:
                    int methodId = BitConverter.ToInt32(ildata, position);
                    position += 4;
                    try
                    {
                        if (mi is ConstructorInfo)
                        {
                            result.Add((MethodBase)module.ResolveMember(methodId, mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes));
                        }
                        else
                        {
                            result.Add((MethodBase)module.ResolveMember(methodId, mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments()));
                        }
                    }
                    catch { } 
                    break;


                default:
                    throw new Exception("Unknown instruction operand; cannot continue. Operand type: " + code.OperandType);
            }
        }
        return result.ToArray();
    }
}

class StackOverflowDetector
{
    // This method will be found:
    static int Recur()
    {
        CheckStackDepth();
        int variable = 1;
        return variable + Recur();
    }

    static void Main(string[] args)
    {
        RecursionDetector();
        Console.WriteLine();
        Console.ReadLine();
    }

    static void RecursionDetector()
    {
        // First decompile all methods in the assembly:
        Dictionary<MethodBase, MethodBase[]> calling = new Dictionary<MethodBase, MethodBase[]>();
        var assembly = typeof(StackOverflowDetector).Assembly;

        foreach (var type in assembly.GetTypes())
        {
            foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).OfType<MethodBase>())
            {
                var body = member.GetMethodBody();
                if (body!=null)
                {
                    var bytes = body.GetILAsByteArray();
                    if (bytes != null)
                    {
                        // Store all the calls of this method:
                        var calls = Decompiler.Decompile(member, bytes);
                        calling[member] = calls;
                    }
                }
            }
        }

        // Check every method:
        foreach (var method in calling.Keys)
        {
            // If method A -> ... -> method A, we have a possible infinite recursion
            CheckRecursion(method, calling, new HashSet<MethodBase>());
        }
    }

现在,方法循环包含递归的事实并不能保证堆栈溢出会发生 - 它只是堆栈溢出异常的最可能的前提条件。简而言之,这意味着此代码将确定堆栈溢出可以发生的代码段,这应该会大大缩小大多数代码。

其他方法

您可以尝试其他一些方法,我在这里没有描述。

  1. 通过托管CLR进程并处理它来处理堆栈溢出。请注意,您仍然无法抓住&#39;它。
  2. 更改所有IL代码,构建另一个DLL,添加对递归的检查。是的,这很有可能(我过去实施了它:-);它很难,并且需要很多代码才能做到正确。
  3. 使用.NET分析API捕获所有方法调用,并使用它来计算堆栈溢出。例如,您可以实现检查,如果您在调用树中遇到相同的方法X次,则会给出一个信号。有一个项目here可以帮助您领先一步。

答案 2 :(得分:8)

我建议创建一个围绕XmlWriter对象的包装器,这样它会计算对WriteStartElement / WriteEndElement的调用量,如果你将标签数量限制为某个数字(fe 100),你就可以抛出一个不同的异常,例如 - InvalidOperation。

这应解决大多数情况下的问题

public class LimitedDepthXmlWriter : XmlWriter
{
    private readonly XmlWriter _innerWriter;
    private readonly int _maxDepth;
    private int _depth;

    public LimitedDepthXmlWriter(XmlWriter innerWriter): this(innerWriter, 100)
    {
    }

    public LimitedDepthXmlWriter(XmlWriter innerWriter, int maxDepth)
    {
        _maxDepth = maxDepth;
        _innerWriter = innerWriter;
    }

    public override void Close()
    {
        _innerWriter.Close();
    }

    public override void Flush()
    {
        _innerWriter.Flush();
    }

    public override string LookupPrefix(string ns)
    {
        return _innerWriter.LookupPrefix(ns);
    }

    public override void WriteBase64(byte[] buffer, int index, int count)
    {
        _innerWriter.WriteBase64(buffer, index, count);
    }

    public override void WriteCData(string text)
    {
        _innerWriter.WriteCData(text);
    }

    public override void WriteCharEntity(char ch)
    {
        _innerWriter.WriteCharEntity(ch);
    }

    public override void WriteChars(char[] buffer, int index, int count)
    {
        _innerWriter.WriteChars(buffer, index, count);
    }

    public override void WriteComment(string text)
    {
        _innerWriter.WriteComment(text);
    }

    public override void WriteDocType(string name, string pubid, string sysid, string subset)
    {
        _innerWriter.WriteDocType(name, pubid, sysid, subset);
    }

    public override void WriteEndAttribute()
    {
        _innerWriter.WriteEndAttribute();
    }

    public override void WriteEndDocument()
    {
        _innerWriter.WriteEndDocument();
    }

    public override void WriteEndElement()
    {
        _depth--;

        _innerWriter.WriteEndElement();
    }

    public override void WriteEntityRef(string name)
    {
        _innerWriter.WriteEntityRef(name);
    }

    public override void WriteFullEndElement()
    {
        _innerWriter.WriteFullEndElement();
    }

    public override void WriteProcessingInstruction(string name, string text)
    {
        _innerWriter.WriteProcessingInstruction(name, text);
    }

    public override void WriteRaw(string data)
    {
        _innerWriter.WriteRaw(data);
    }

    public override void WriteRaw(char[] buffer, int index, int count)
    {
        _innerWriter.WriteRaw(buffer, index, count);
    }

    public override void WriteStartAttribute(string prefix, string localName, string ns)
    {
        _innerWriter.WriteStartAttribute(prefix, localName, ns);
    }

    public override void WriteStartDocument(bool standalone)
    {
        _innerWriter.WriteStartDocument(standalone);
    }

    public override void WriteStartDocument()
    {
        _innerWriter.WriteStartDocument();
    }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        if (_depth++ > _maxDepth) ThrowException();

        _innerWriter.WriteStartElement(prefix, localName, ns);
    }

    public override WriteState WriteState
    {
        get { return _innerWriter.WriteState; }
    }

    public override void WriteString(string text)
    {
        _innerWriter.WriteString(text);
    }

    public override void WriteSurrogateCharEntity(char lowChar, char highChar)
    {
        _innerWriter.WriteSurrogateCharEntity(lowChar, highChar);
    }

    public override void WriteWhitespace(string ws)
    {
        _innerWriter.WriteWhitespace(ws);
    }

    private void ThrowException()
    {
        throw new InvalidOperationException(string.Format("Result xml has more than {0} nested tags. It is possible that xslt transformation contains an endless recursive call.", _maxDepth));
    }
}

答案 3 :(得分:4)

这个答案是给@WilliamJockusch的。

  

我想知道是否有一般追踪方式   StackOverflowExceptions。换句话说,假设我有无限的   在我的代码中的某处递归,但我不知道在哪里。我想要   通过某种方式跟踪它比通过代码更容易   到处都是,直到我看到它发生。我不在乎多么hackish   它是。例如,拥有一个我可以的模块会很棒   激活,甚至可能从另一个线程激活,轮询堆栈   深度和抱怨,如果它达到我认为“太高”的水平。对于   例如,我可能将“太高”设置为600帧,如果确定的话   堆栈太深,这一定是个问题。是这样的   可能。另一个例子是记录每个第1000个方法调用   在我的代码中调试输出。这可能会得到一些   过低的证据会很好,而且可能不会   把输出放得太厉害了。关键是它不能涉及   在发生溢出的地方写一张支票。因为整个   问题是我不知道那是哪里。最好是解决方案   不应该取决于我的开发环境是什么样的;即,   它不应该假设我通过特定的工具集使用C#(例如   VS)。

听起来你很想听到一些调试技术来捕捉这个StackOverflow所以我想我会分享一些让你尝试的。

1。记忆转储。

Pro的:内存转储是解决堆栈溢出原因的可靠方法。 C#MVP&amp;我一起解决了SO问题,然后他继续写博客here

此方法是追踪问题的最快方法。

此方法不需要您按照日志中的步骤重现问题。

Con's :内存转储非常大,您必须在此过程中附加AdPlus / procdump。

2。面向方面编程。

Pro :这可能是您实现从任何方法检查调用堆栈大小的代码的最简单方法,而无需在应用程序的每个方法中编写代码。有许多AOP Frameworks允许您在通话前后拦截。

将告诉您导致Stack Overflow的方法。

允许您检查应用程序中所有方法的进入和退出时的StackTrace().FrameCount

Con's :它会对性能产生影响 - 每个方法都会将挂钩嵌入到IL中,而您无法将其“取消激活”。

这在某种程度上取决于您的开发环境工具集。

3。记录用户活动。

一周前,我试图追捕几个难以重现的问题。我发布了此质量检查User Activity Logging, Telemetry (and Variables in Global Exception Handlers)。我得出的结论是一个非常简单的用户操作记录器,用于查看在发生任何未处理的异常时如何在调试器中重现问题。

Pro :您可以随意打开或关闭它(即订阅活动)。

跟踪用户操作不需要拦截每个方法。

您可以计算订阅方法的数量远比使用AOP 更简单。

日志文件相对较小,专注于重现问题所需执行的操作。

它可以帮助您了解用户如何使用您的应用程序。

Con's :不适合Windows服务,我确信有更好的工具,例如Web应用

必须告诉您导致堆栈溢出的方法。

要求您手动重现日志,而不是内存转储,您可以在其中获取并立即调试。

也许您可以尝试我上面提到的所有技术以及@atlaste发布的一些技巧,并告诉我们您发现哪一个是在PROD环境/等中运行的最简单/最快/最脏/最可接受的。

无论如何,祝你好运追踪这个SO。

答案 4 :(得分:3)

如果您的应用程序依赖于3d-party代码(在Xsl-scripts中),那么您必须首先决定是否要防范它们中的错误。 如果你真的想要辩护那么我认为你应该执行你的逻辑,这个逻辑在单独的AppDomain中容易出现外部错误。 捕获StackOverflowException并不好。

另请查看此question

答案 5 :(得分:3)

今天我有一个stackoverflow,我读了你的一些帖子,并决定帮助垃圾收集器。

我曾经有过这样的无限循环:

    class Foo
    {
        public Foo()
        {
            Go();
        }

        public void Go()
        {
            for (float i = float.MinValue; i < float.MaxValue; i+= 0.000000000000001f)
            {
                byte[] b = new byte[1]; // Causes stackoverflow
            }
        }
    }

相反,让资源超出范围,如下所示:

class Foo
{
    public Foo()
    {
        GoHelper();
    }

    public void GoHelper()
    {
        for (float i = float.MinValue; i < float.MaxValue; i+= 0.000000000000001f)
        {
            Go();
        }
    }

    public void Go()
    {
        byte[] b = new byte[1]; // Will get cleaned by GC
    }   // right now
}

它对我有用,希望它对某人有所帮助。

答案 6 :(得分:2)

使用.NET 4.0您可以将System.Runtime.ExceptionServices中的HandleProcessCorruptedStateExceptions属性添加到包含try / catch块的方法中。这确实有效!也许不推荐但是有效。

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;

namespace ExceptionCatching
{
    public class Test
    {
        public void StackOverflow()
        {
            StackOverflow();
        }

        public void CustomException()
        {
            throw new Exception();
        }

        public unsafe void AccessViolation()
        {
            byte b = *(byte*)(8762765876);
        }
    }

    class Program
    {
        [HandleProcessCorruptedStateExceptions]
        static void Main(string[] args)
        {
            Test test = new Test();
            try {
                //test.StackOverflow();
                test.AccessViolation();
                //test.CustomException();
            }
            catch
            {
                Console.WriteLine("Caught.");
            }

            Console.WriteLine("End of program");

        }

    }      
}

答案 7 :(得分:0)

从它的外观来看,除了开始另一个过程之外,似乎没有办法处理StackOverflowException。在其他人要求之前,我尝试使用AppDomain,但这不起作用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;

namespace StackOverflowExceptionAppDomainTest
{
    class Program
    {
        static void recrusiveAlgorithm()
        {
            recrusiveAlgorithm();
        }
        static void Main(string[] args)
        {
            if(args.Length>0&&args[0]=="--child")
            {
                recrusiveAlgorithm();
            }
            else
            {
                var domain = AppDomain.CreateDomain("Child domain to test StackOverflowException in.");
                domain.ExecuteAssembly(Assembly.GetEntryAssembly().CodeBase, new[] { "--child" });
                domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
                {
                    Console.WriteLine("Detected unhandled exception: " + e.ExceptionObject.ToString());
                };
                while (true)
                {
                    Console.WriteLine("*");
                    Thread.Sleep(1000);
                }
            }
        }
    }
}

但是,如果您最终使用单独进程解决方案,我建议您使用Process.ExitedProcess.StandardOutput并自行处理错误,以便为用户提供更好的体验。

答案 8 :(得分:0)

@WilliamJockusch,如果我理解你的关注,那么(从数学的角度来看)不可能总是识别无限递归,因为它意味着解决Halting problem。要解决此问题,您需要Super-recursive algorithm(例如Trial-and-error predicates)或能hypercompute的机器(following section中解释的示例 - 可用作预览 - this book)。

从实际角度来看,你必须知道:

  • 您在给定时间剩余的堆栈内存
  • 特定输出在给定时间递归方法需要多少堆栈内存。

请记住,使用当前的计算机,由于多任务处理,这些数据非常可变,我还没有听说过执行该任务的软件。

如果不清楚,请告诉我。

答案 9 :(得分:-2)

您可以每隔几次调用Environment.StackTrace读取此属性,如果堆栈跟踪超出您预设的特定阈值,则可以返回该功能。

您还应该尝试用循环替换一些递归函数。

相关问题