分配引用类型时 c# 中的奇怪 stackoverflow

Weird stackoverflow in c# when allocating reference types

在做一些花哨的代码生成时,我遇到了一个我不明白的堆栈溢出。

我的代码基本上是这样的:

static Tuple<string, int>[] DoWork() 
{
    // [ call some methods ]
    Tuple<string, int>[] tmp = new Tuple<string, int>[100];
    tmp[0] = new Tuple<string, int>("blah 1", 0);
    tmp[1] = new Tuple<string, int>("blah 2", 1);
    tmp[2] = new Tuple<string, int>("blah 3", 2);
    // ...
    tmp[99] = new Tuple<string, int>("blah 99", 99);
    return tmp;
}

如果您使用像此处 (100) 这样的小数字,则一切正常。如果数字很大,就会发生奇怪的事情。在我的例子中,我尝试发出大约 10K 行这样的代码,这触发了堆栈溢出异常。

所以...为什么我觉得这很奇怪:

重现奇怪...

我无法在最小测试用例中重现 Whosebug,但我确实注意到它似乎是在 64 位 .NET 4.5 上触发的。我可以提供一些证据来证明正在发生的事情。

另请注意,实际代码使用 Reflection.Emit 代码来生成此代码...它不像代码本身具有所有这些代码行...发出的 IL 代码是正确的顺便说一句。

In Visual Studio - 在最后一行放置一个断点。注意反汇编中堆栈指针的使用(ASM,不是 IL)。

现在向代码中添加一个新行 -- 例如tmp[100] = // the usuals。在这里也放置一个断点,并注意使用的堆栈 space 增长。

至于尝试使用 Reflection.Emit 使用最小测试用例进行重现,这是代码(它并没有足够奇怪地重现问题 - 但非常接近我所做的触发堆栈溢出......它应该给出我正在尝试做的一些图片,也许其他人可以使用它生成一个可行的测试用例)。这里是:

public static void Foo()
{
    Console.WriteLine("Foo!");
}

static void Main(string[] args)
{
    // all this just to invoke one opcode with no arguments!
    var assemblyName = new AssemblyName("MyAssembly");

    var assemblyBuilder =
        AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,
        AssemblyBuilderAccess.RunAndCollect);

    // Create module
    var moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule");

    var type = moduleBuilder.DefineType("MyType", TypeAttributes.Public, typeof(object));

    var method = type.DefineMethod("Test", System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static, System.Reflection.CallingConventions.Standard, typeof(Tuple<string, int>[]), new Type[0]);

    ILGenerator gen = method.GetILGenerator();
    int count = 0x10000;

    gen.Emit(OpCodes.Call, typeof(WhosebugGenerator).GetMethod("Foo"));

    var loc = gen.DeclareLocal(typeof(Tuple<string, int>[]));
    gen.Emit(OpCodes.Ldc_I4, count);
    gen.Emit(OpCodes.Newarr, typeof(Tuple<string, int>));
    gen.Emit(OpCodes.Stloc, loc);

    for (int i = 0; i < count; ++i)
    {
        // Load array
        gen.Emit(OpCodes.Ldloc, loc);
        gen.Emit(OpCodes.Ldc_I4, i);

        // Construct tuple:
        gen.Emit(OpCodes.Ldstr, "This is the string");
        gen.Emit(OpCodes.Ldc_I4, i);
        gen.Emit(OpCodes.Newobj, typeof(Tuple<string, int>).GetConstructor(new[] { typeof(string), typeof(int) }));

        // Store in the array
        gen.Emit(OpCodes.Stelem_Ref);
    }

    // Return the result
    gen.Emit(OpCodes.Ldloc, loc);
    gen.Emit(OpCodes.Ret);

    var materialized = type.CreateType();

    var tmp = checked((Tuple<string, int>[])materialized.GetMethod("Test").Invoke(null, new object[0]));

    int total = 0;
    foreach (var item in tmp)
    {
        total += item.Item1.Length + item.Item2;
    }
    Console.WriteLine("Total: {0}", total);
    Console.ReadLine();
}

我的问题

这样的东西怎么会产生国有企业?这里发生了什么?无论如何,为什么在这种情况下要把东西放在堆栈上?

你生成的代码有一些问题,但更深层次的问题在于JIT引擎

tl;博士

函数中的每个 new 运算符都需要在堆栈中有一个 DWORD,甚至 new object(),无论优化和 release/debug 模式如何,它都会存在!这实际上意味着根据您的堆栈大小,new 关键字在函数中出现的次数受到限制。

导致问题的原因是什么?

SOF 是因为 JIT 生成的代码试图在堆栈上分配过多的 space(使用 sub esp <number>)。 JIT 在检查函数中堆栈的使用情况后选择分配多少。如果你有很多局部变量,你的函数将不得不在堆栈上使用更多内存,而 JIT 无法知道运行时堆栈有多大,因此它会在运行时崩溃。一个临时解决方案可能是使用编译器标志等使堆栈更大。

谁的错?

你的代码没有在堆栈上使用很多变量,事实上,你明确地只使用了一个,指向数组的指针。

但是,您的代码(在没有优化的情况下使用时)会创建许多 "temporary one-time" 个变量,每个变量对应于您在 new Tuple<...> 中使用的每个 string 和每个 integer。它们将随着优化打开而消失。

即,而不是像这样:

var x = new Tuple<string, int>("blah 1", 0);
tmp[0] = x;
x = new Tuple<string, int>("blah 2", 1);
tmp[1] = x;

你最终得到这样的结果:

var str1 = "blah 1";
var int1 = 0;
var x = new Tuple<string, int>(str1, int1);
tmp[0] = x;
var str2 = "blah 2";
var int2 = 1;
var x2 = new Tuple<string, int>(str2, int2);
tmp[1] = x2;

正如您在反汇编中看到的那样:

            tmp[0] = new Tuple<string, int>("blah 1", 0);
00FB26AE  mov         ecx,6D5203BCh  
00FB26B3  call        00F32100  
00FB26B8  mov         dword ptr [ebp-48h],eax  
00FB26BB  push        0  
00FB26BD  mov         edx,dword ptr ds:[3B721F0h]  
00FB26C3  mov         ecx,dword ptr [ebp-48h]  
00FB26C6  call        6D47C0DC  
00FB26CB  push        dword ptr [ebp-48h]  
00FB26CE  mov         ecx,dword ptr [ebp-3Ch]   // ecx = (ebp - 0x3C) [ == tmp ]
00FB26D1  xor         edx,edx  
00FB26D3  call        6E2883FF                  // ecx.setElement(0, ebp - 0x48) 
            tmp[1] = new Tuple<string, int>("blah 2", 1);
00FB26D8  mov         ecx,6D5203BCh  
00FB26DD  call        00F32100  
00FB26E2  mov         dword ptr [ebp-4Ch],eax  
00FB26E5  push        1  
00FB26E7  mov         edx,dword ptr ds:[3B721F4h]  
00FB26ED  mov         ecx,dword ptr [ebp-4Ch]  
00FB26F0  call        6D47C0DC  
00FB26F5  push        dword ptr [ebp-4Ch]
00FB26F8  mov         ecx,dword ptr [ebp-3Ch]  // ecx = (ebp - 0x3C) [ == tmp ]
00FB26FB  mov         edx,1  
00FB2700  call        6E2883FF                 // ecx.setElement = (1, ebp - 0x4C)

让我们将您的代码更改为如下内容:

Tuple<string, int>[] tmp = new Tuple<string, int>[10000];
var str = "blah 1";
var i = 0;
var x = new Tuple<string, int>(str, i);
tmp[0] = x;

str = "blah 2";
i = 1;
x = new Tuple<string, int>(str, i);
tmp[1] = x;

此代码生成的函数在堆栈堆栈上使用的内存较少。然而,经过更深入的检查,该代码还将在堆栈上为每个 new Tuple 生成一个 "one time" 变量,因此通过增加分配量,您也​​会增加堆栈使用量。

            str = "blah 2";
008A26E9  mov         eax,dword ptr ds:[32421F4h]  
008A26EF  mov         dword ptr [ebp-10h],eax  
            i = 1;
008A26F2  mov         dword ptr [ebp-8],1  
            x = new Tuple<string, int>(str, i);
008A26F9  mov         ecx,6D5203BCh  
008A26FE  call        006C2100  
008A2703  mov         dword ptr [ebp-20h],eax           // this is the one-time variable
008A2706  push        dword ptr [ebp-8]  
008A2709  mov         ecx,dword ptr [ebp-20h]  
008A270C  mov         edx,dword ptr [ebp-10h]  
008A270F  call        6D47C0DC  
008A2714  mov         eax,dword ptr [ebp-20h]  
008A2717  mov         dword ptr [ebp-14h],eax  
            tmp[1] = x;
008A271A  push        dword ptr [ebp-14h]  
008A271D  mov         ecx,dword ptr [ebp-0Ch]  
008A2720  mov         edx,1  
008A2725  call        6E2883FF  

            str = "blah 3";
008A272A  mov         eax,dword ptr ds:[32421F8h]  

            str = "blah 3";
008A2730  mov         dword ptr [ebp-10h],eax  
            i = 2;
008A2733  mov         dword ptr [ebp-8],2  
            x = new Tuple<string, int>(str, i);
008A273A  mov         ecx,6D5203BCh  
008A273F  call        006C2100  
008A2744  mov         dword ptr [ebp-24h],eax           // this is the one-time variable
008A2747  push        dword ptr [ebp-8]  
008A274A  mov         ecx,dword ptr [ebp-24h]  
008A274D  mov         edx,dword ptr [ebp-10h]  
008A2750  call        6D47C0DC  
008A2755  mov         eax,dword ptr [ebp-24h]  
008A2758  mov         dword ptr [ebp-14h],eax  
            tmp[2] = x;
008A275B  push        dword ptr [ebp-14h]  
008A275E  mov         ecx,dword ptr [ebp-0Ch]  
008A2761  mov         edx,2  
008A2766  call        6E2883FF  

更糟糕的是,即使在启用优化的发布模式下,它也会在堆栈中生成这个 "one time" 变量!

这让我相信这是 JIT 引擎或编译器本身的问题。因此,让我们检查一下编译器给我们的 MSIL:

ldstr    aBlah2         // "blah 2"
stloc.1                 // Pop value from stack into local variable 1
ldc.i4.1                // Push 1 onto the stack as I4
stloc.2                 // Pop value from stack into local variable 2
ldloc.1                 // Load local variable 1 onto stack
ldloc.2                 // Load local variable 2 onto stack
newobj   instance void class [mscorlib]System.Tuple`2<string, int32>::.ctor(var<u1>, !!T0) // Create a new object
stloc.3                 // Pop value from stack into local variable 3
ldloc.0                 // Load local variable 0 onto stack
ldc.i4.1                // Push 1 onto the stack as I4
ldloc.3                 // Load local variable 3 onto stack
stelem.ref              // Replace array element at index with the ref value on the s

其中,当评论时,是:

push "blah 2"
local_str = pop // "blah 2"
push 1
local_int = pop
push local_str // "blah 2"
push local_int // 1

push new Tuple(...)
local_tuple = pop
push local_array
push 0
push local_tuple
pop[pop] = pop (i.e arr[indx] = value)

所以 JIT 代码通常看起来没问题。

因此我断定这是JIT引擎的问题

通常,这意味着对于 Tuple class 的每个构造,都会在堆栈中使用不必要的 DWORD,这对于像您这样的情况非常糟糕,但不会'对于不像您的代码那样做很多 "manual" 赋值的程序没有任何意义。

即使是小函数也会出现这种情况,真的很奇怪!

在 x64 位中,以下 C# 代码:

var a = new object();
a = new object();
a = new object();
a = new object();
a = new object();
a = new object();
a = new object();

编译并 JIT 到:

            a = new object();
00007FFAD0033B5F  call        00007FFB2F662300  
00007FFAD0033B64  mov         qword ptr [rsp+40h],rax  
00007FFAD0033B69  mov         rax,qword ptr [rsp+40h]  
00007FFAD0033B6E  mov         qword ptr [rsp+48h],rax  
00007FFAD0033B73  mov         rcx,qword ptr [rsp+48h]  
00007FFAD0033B78  call        00007FFB2E455BC0  
00007FFAD0033B7D  nop  
            a = new object();
00007FFAD0033B7E  lea         rcx,[7FFB2E6611B8h]  
00007FFAD0033B85  call        00007FFB2F662300  
00007FFAD0033B8A  mov         qword ptr [rsp+50h],rax  
00007FFAD0033B8F  mov         rax,qword ptr [rsp+50h]  
00007FFAD0033B94  mov         qword ptr [rsp+58h],rax  
00007FFAD0033B99  mov         rcx,qword ptr [rsp+58h]  
00007FFAD0033B9E  call        00007FFB2E455BC0  
00007FFAD0033BA3  nop  
// and so on....

并产生许多未使用的 QWORDs。

在 x86 上,代码如下所示:

            a = new object();
00882687  mov         ecx,6D512554h  
0088268C  call        00652100  
00882691  mov         dword ptr [ebp-0Ch],eax  
00882694  mov         ecx,dword ptr [ebp-0Ch]  
00882697  call        6D410B40  
0088269C  nop  
            a = new object();
0088269D  mov         ecx,6D512554h  
008826A2  call        00652100  
008826A7  mov         dword ptr [ebp-10h],eax  
008826AA  mov         ecx,dword ptr [ebp-10h]  
008826AD  call        6D410B40  
008826B2  nop  
// and so on...

效率更高,但 "wastes" 很多 DWORDS

你能做什么?

其实不多。问题的根源在于 JIT 必须在堆栈上为每个 new 运算符分配一个 DWORD(也许它可以跟踪它们?我说不准)。您唯一的解决方案(未修复)是制作多个函数,每个函数将处理您需要的一部分作业。