- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
一个非常简单的示例应用程序(.NET 4.6.2)在的递归深度为12737 时生成StackOverflowException,如果最内部函数调用引发异常,则递减深度为 10243 ,这是可以预期的,并且可以。
如果我使用Lazy<T>
暂时保留中间结果,则如果未引发异常,则递归深度为 2207 ,如果已引发异常,则发生递归深度为 105 。
注意:深度为 105 的StackOverflowException仅在编译为x64时才可观察到。使用x86(32位)时,效果首先出现在 4272 深度处。 Mono(就像https://repl.it所使用的一样)可以在深度达到74200 的情况下正常工作。
StackOverflowException不会在深度递归内发生,而是在升回到主例程时发生。对finally块进行一定深度的处理,然后程序死亡:
Exception System.InvalidOperationException at 105
Finally at 105
...
Exception System.InvalidOperationException at 55
Finally at 55
Exception System.InvalidOperationException at 54
Finally at 54
Process is terminated due to StackOverflowException.
The program '[xxxxx] Test.vshost.exe' has exited with code -2147023895 (0x800703e9).
public class Program
{
private class Test
{
private int maxDepth;
private int CalculateWithLazy(int depth)
{
try
{
var lazy = new Lazy<int>(() => this.Calculate(depth));
return lazy.Value;
}
catch (Exception e)
{
Console.WriteLine("Exception " + e.GetType() + " at " + depth);
throw;
}
finally
{
Console.WriteLine("Finally at " + depth);
}
}
private int Calculate(int depth)
{
if (depth >= this.maxDepth) throw new InvalidOperationException("Max. recursion depth reached.");
return this.CalculateWithLazy(depth + 1);
}
public void Run()
{
for (int i = 1; i < 100000; i++)
{
this.maxDepth = i;
try
{
Console.WriteLine("MaxDepth: " + i);
this.CalculateWithLazy(0);
}
catch { /* ignore */ }
}
}
}
public static void Main(string[] args)
{
var test = new Test();
test.Run();
Console.Read();
}
Lazy<T>
的情况下重现该问题。
[MethodImpl(MethodImplOptions.NoInlining)]
private int Calculate(int depth)
{
try
{
if (depth >= this.maxDepth) throw new InvalidOperationException("Max. recursion depth reached.");
return this.Calculate2(depth + 1);
}
catch
{
throw;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int Calculate2(int depth) // just to prevent the compiler from tail-recursion-optimization
{
return this.Calculate(depth);
}
public void Run()
{
for (int i = 1; i < 100000; i++)
{
this.maxDepth = i;
try
{
Console.WriteLine("MaxDepth: " + i);
this.Calculate(0);
}
catch(Exception e)
{
Console.WriteLine("Finished with " + e.GetType());
}
}
}
最佳答案
The problem can be reproduced without the usage of
Lazy<T>
, just by having a try-catch-throw block in the recursive method.
internal class Program
{
private int _maxDepth;
[MethodImpl(MethodImplOptions.NoInlining)]
private int Calculate(int depth)
{
try
{
Console.WriteLine("In try at depth {0}: stack frame count = {1}", depth, new StackTrace().FrameCount);
if (depth >= _maxDepth)
throw new InvalidOperationException("Max. recursion depth reached.");
return Calculate2(depth + 1);
}
catch
{
Console.WriteLine("In catch at depth {0}: stack frame count = {1}", depth, new StackTrace().FrameCount);
throw;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int Calculate2(int depth) => Calculate(depth);
public void Run()
{
try
{
_maxDepth = 10;
Calculate(0);
}
catch (Exception e)
{
Console.WriteLine("Finished with " + e.GetType());
}
}
public static void Main() => new Program().Run();
}
似乎可以验证该假设:
In try at depth 0: stack frame count = 3
In try at depth 1: stack frame count = 5
In try at depth 2: stack frame count = 7
In try at depth 3: stack frame count = 9
In try at depth 4: stack frame count = 11
In try at depth 5: stack frame count = 13
In try at depth 6: stack frame count = 15
In try at depth 7: stack frame count = 17
In try at depth 8: stack frame count = 19
In try at depth 9: stack frame count = 21
In try at depth 10: stack frame count = 23
In catch at depth 10: stack frame count = 23
In catch at depth 9: stack frame count = 21
In catch at depth 8: stack frame count = 19
In catch at depth 7: stack frame count = 17
In catch at depth 6: stack frame count = 15
In catch at depth 5: stack frame count = 13
In catch at depth 4: stack frame count = 11
In catch at depth 3: stack frame count = 9
In catch at depth 2: stack frame count = 7
In catch at depth 1: stack frame count = 5
In catch at depth 0: stack frame count = 3
Finished with System.InvalidOperationException
好吧...不这不是那么简单。
The other form of unwind is the actual popping of the CPU stack. This doesn’t happen as eagerly as the popping of the SEH records. On X86, EBP is used as the frame pointer for methods containing SEH. ESP points to the top of the stack, as always. Until the stack is actually unwound, all the handlers are executed on top of the faulting exception frame. So the stack actually grows when a handler is called for the first or second pass. EBP is set to the frame of the method containing a filter or finally clause so that local variables of that method will be in scope.
The actual popping of the stack doesn’t occur until the catching ‘except’ clause is executed.
internal class Program
{
private int _maxDepth;
private UIntPtr _stackStart;
[MethodImpl(MethodImplOptions.NoInlining)]
private int Calculate(int depth)
{
try
{
Console.WriteLine("In try at depth {0}: stack frame count = {1}, stack offset = {2}",depth, new StackTrace().FrameCount, GetLooseStackOffset());
if (depth >= _maxDepth)
throw new InvalidOperationException("Max. recursion depth reached.");
return Calculate2(depth + 1);
}
catch
{
Console.WriteLine("In catch at depth {0}: stack frame count = {1}, stack offset = {2}", depth, new StackTrace().FrameCount, GetLooseStackOffset());
throw;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int Calculate2(int depth) => Calculate(depth);
public void Run()
{
try
{
_stackStart = GetSomePointerNearTheTopOfTheStack();
_maxDepth = 10;
Calculate(0);
}
catch (Exception e)
{
Console.WriteLine("Finished with " + e.GetType());
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe UIntPtr GetSomePointerNearTheTopOfTheStack()
{
int dummy;
return new UIntPtr(&dummy);
}
private int GetLooseStackOffset() => (int)((ulong)_stackStart - (ulong)GetSomePointerNearTheTopOfTheStack());
public static void Main() => new Program().Run();
}
结果如下:
In try at depth 0: stack frame count = 3, stack offset = 384
In try at depth 1: stack frame count = 5, stack offset = 752
In try at depth 2: stack frame count = 7, stack offset = 1120
In try at depth 3: stack frame count = 9, stack offset = 1488
In try at depth 4: stack frame count = 11, stack offset = 1856
In try at depth 5: stack frame count = 13, stack offset = 2224
In try at depth 6: stack frame count = 15, stack offset = 2592
In try at depth 7: stack frame count = 17, stack offset = 2960
In try at depth 8: stack frame count = 19, stack offset = 3328
In try at depth 9: stack frame count = 21, stack offset = 3696
In try at depth 10: stack frame count = 23, stack offset = 4064
In catch at depth 10: stack frame count = 23, stack offset = 13024
In catch at depth 9: stack frame count = 21, stack offset = 21888
In catch at depth 8: stack frame count = 19, stack offset = 30752
In catch at depth 7: stack frame count = 17, stack offset = 39616
In catch at depth 6: stack frame count = 15, stack offset = 48480
In catch at depth 5: stack frame count = 13, stack offset = 57344
In catch at depth 4: stack frame count = 11, stack offset = 66208
In catch at depth 3: stack frame count = 9, stack offset = 75072
In catch at depth 2: stack frame count = 7, stack offset = 83936
In catch at depth 1: stack frame count = 5, stack offset = 92800
In catch at depth 0: stack frame count = 3, stack offset = 101664
Finished with System.InvalidOperationException
哎呀。是的,当我们处理异常时,堆栈实际上会增长。
_maxDepth = 1000
处,执行在以下位置结束:
In catch at depth 933: stack frame count = 1869, stack offset = 971232
In catch at depth 932: stack frame count = 1867, stack offset = 980096
In catch at depth 931: stack frame count = 1865, stack offset = 988960
In catch at depth 930: stack frame count = 1863, stack offset = 997824
Process is terminated due to StackOverflowException.
因此,根据我们自己的代码,大约997824字节的已使用堆栈空间非常接近Windows上1 MB的默认线程堆栈大小。调用CLR代码应弥补差异。
catch
子句是否与正确的异常类型匹配,并在存在的情况下执行when
的catch (...) when (...)
部分。 When an exception occurs, the system walks the list of
EXCEPTION_REGISTRATION
structures until it finds a handler for the exception. Once a handler is found, the system walks the list again, up to the node that will handle the exception. During this second traversal, the system calls each handler function a second time. The key distinction is that in the second call, the value 2 is set in the exception flags. This value corresponds toEH_UNWINDING
.[...]
After an exception is handled and all the previous exception frames have been called to unwind, execution continues wherever the handling callback decides.
EH_UNWINDING
标志之外,第二遍的实现与第一遍一样。这意味着有问题的堆栈仍会保留在该点,直到最终处理程序决定从何处恢复执行为止。
The stack pointer moves 36 bytes for a 32-Bit process, but whopping 8976 bytes for a 64-bit process here while unwinding the stack. What's the explanation for this?
Because on the x86 each function that uses SEH has this aforementioned construct as part of its prolog, the x86 is said to use frame based exception handling. There are a couple of problems with this approach:
- Because the exception information is stored on the stack, it is susceptible to buffer overflow attacks.
- Overhead. Exceptions are, well, exceptional, which means the exception will not occur in the common case. Regardless, every time a function is entered that uses SEH, these extra instructions are executed.
Because the x64 was a chance to do away with a lot of the cruft that had been hanging around for decades, SEH got an overhaul that addressed both issues mentioned above. On the x64, SEH has become table-based, which means when the source code is compiled, a table is created that fully describes all the exception handling code within the module. This table is then stored as part of the PE header. If an exception occurs, the exception table is parsed by Windows to find the appropriate exception handler to execute. Because exception handling information is tucked safely away in the PE header, it is no longer susceptible to buffer overflow attacks. In addition, because the exception table is generated as part of the compilation process, no runtime overhead (in the form of push and pop instructions) is incurred during normal processing.
Of course, table-based exception handling schemes have a couple of negative aspects of their own. For example, table-based schemes tend to take more space in memory than stack-based schemes. Also, while overhead in the normal execution path is reduced, the overhead it takes to process an exception is significantly higher than in frame-based approaches. Like everything in life, there are trade-offs to consider when evaluating whether the table-based or a frame-based approach to exception handling is "best."
Both IA64 and AMD64 have a model for exception handling that avoids reliance on an explicit handler chain that starts in TLS and is threaded through the stack. Instead, exception handling relies on the fact that on 64-bit systems we can perfectly unwind a stack. And this ability is itself due to the fact that these chips are severely constrained on the calling conventions they support.
[...]
Anyway, on 64-bit systems the correspondence between an activation record on the stack and the exception record that applies to it is not achieved through an FS:[0] chain. Instead, unwinding of the stack reveals the code addresses that correspond to a particular activation record. These instruction pointers of the method are looked up in a table to find out whether there are any__try/__except/__finally clauses that cover these code addresses. This table also indicates how to proceed with the unwind by describing the actions of the method epilog.
Calculate
,如下所示:
private int Calculate(int depth)
{
try
{
if (depth >= _maxDepth)
throw new InvalidOperationException("Max. recursion depth reached.");
return Calculate2(depth + 1);
}
catch
{
if (depth == _maxDepth)
{
Console.ReadLine();
}
throw;
}
}
我在
Console.ReadLine();
上设置了一个断点,并查看了 native 调用堆栈以及每帧上的堆栈指针寄存器的值:
fffffffffffffffe
和
0000000000008000
在我看来很奇怪,但是无论如何,这表明每帧消耗了多少堆栈空间。 Windows Native API(ntdll.dll)中发生了很多事情,CLR添加了一些东西。
clr.dll!ClrUnwindEx
,因为该函数是
quite small但使用了很多堆栈空间:
void ClrUnwindEx(EXCEPTION_RECORD* pExceptionRecord, UINT_PTR ReturnValue, UINT_PTR TargetIP, UINT_PTR TargetFrameSp)
{
PVOID TargetFrame = (PVOID)TargetFrameSp;
CONTEXT ctx;
RtlUnwindEx(TargetFrame,
(PVOID)TargetIP,
pExceptionRecord,
(PVOID)ReturnValue, // ReturnValue
&ctx,
NULL); // HistoryTable
// doesn't return
UNREACHABLE();
}
它在堆栈上定义了一个
CONTEXT
变量,即
a large struct。我只能假设64位SEH函数将它们的堆栈空间用于相似的目的。
#include "stdafx.h"
#include <iostream>
__declspec(noinline) static char* GetSomePointerNearTheTopOfTheStack()
{
char dummy;
return &dummy;
}
int main()
{
auto start = GetSomePointerNearTheTopOfTheStack();
try
{
throw 42;
}
catch (...)
{
auto here = GetSomePointerNearTheTopOfTheStack();
std::cout << "Difference in " << (sizeof(char*) * 8) << "-bit: " << (start - here) << std::endl;
}
return 0;
}
结果如下:
Difference in 32-bit: 2224
Difference in 64-bit: 9744
这进一步表明,这不仅是CLR事情,而且还归因于基本的SEH实现差异。
关于c# - 引发异常时,带有Lazy <T>的StackOverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47367058/
#include using namespace std; class C{ private: int value; public: C(){ value = 0;
这个问题已经有答案了: What is the difference between char a[] = ?string?; and char *p = ?string?;? (8 个回答) 已关闭
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 此帖子已于 8 个月
除了调试之外,是否有任何针对 c、c++ 或 c# 的测试工具,其工作原理类似于将独立函数复制粘贴到某个文本框,然后在其他文本框中输入参数? 最佳答案 也许您会考虑单元测试。我推荐你谷歌测试和谷歌模拟
我想在第二台显示器中移动一个窗口 (HWND)。问题是我尝试了很多方法,例如将分辨率加倍或输入负值,但它永远无法将窗口放在我的第二台显示器上。 关于如何在 C/C++/c# 中执行此操作的任何线索 最
我正在寻找 C/C++/C## 中不同类型 DES 的现有实现。我的运行平台是Windows XP/Vista/7。 我正在尝试编写一个 C# 程序,它将使用 DES 算法进行加密和解密。我需要一些实
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
有没有办法强制将另一个 窗口置于顶部? 不是应用程序的窗口,而是另一个已经在系统上运行的窗口。 (Windows, C/C++/C#) 最佳答案 SetWindowPos(that_window_ha
假设您可以在 C/C++ 或 Csharp 之间做出选择,并且您打算在 Windows 和 Linux 服务器上运行同一服务器的多个实例,那么构建套接字服务器应用程序的最明智选择是什么? 最佳答案 如
你们能告诉我它们之间的区别吗? 顺便问一下,有什么叫C++库或C库的吗? 最佳答案 C++ 标准库 和 C 标准库 是 C++ 和 C 标准定义的库,提供给 C++ 和 C 程序使用。那是那些词的共同
下面的测试代码,我将输出信息放在注释中。我使用的是 gcc 4.8.5 和 Centos 7.2。 #include #include class C { public:
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我的客户将使用名为 annoucement 的结构/类与客户通信。我想我会用 C++ 编写服务器。会有很多不同的类继承annoucement。我的问题是通过网络将这些类发送给客户端 我想也许我应该使用
我在 C# 中有以下函数: public Matrix ConcatDescriptors(IList> descriptors) { int cols = descriptors[0].Co
我有一个项目要编写一个函数来对某些数据执行某些操作。我可以用 C/C++ 编写代码,但我不想与雇主共享该函数的代码。相反,我只想让他有权在他自己的代码中调用该函数。是否可以?我想到了这两种方法 - 在
我使用的是编写糟糕的第 3 方 (C/C++) Api。我从托管代码(C++/CLI)中使用它。有时会出现“访问冲突错误”。这使整个应用程序崩溃。我知道我无法处理这些错误[如果指针访问非法内存位置等,
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,因为
我有一些 C 代码,将使用 P/Invoke 从 C# 调用。我正在尝试为这个 C 函数定义一个 C# 等效项。 SomeData* DoSomething(); struct SomeData {
这个问题已经有答案了: Why are these constructs using pre and post-increment undefined behavior? (14 个回答) 已关闭 6
我是一名优秀的程序员,十分优秀!