Why does a program with a PEVerified Stack Overflow Scenario (maxstack) Not Crash the CLR?

2.4k views Asked by At

I can write, compile and successfully run the following IL program with a .maxstack size set to 1 which is too low because the program has two values on the stack at one point in time (i.e. 2+2==4). This program does not crash in the CLR and finishes executing with all the expected output of "Hello World" followed by the number 4.

However this program will (rightfully) not pass PEVerify which points out a stack overflow exception with the following message:

Microsoft (R) .NET Framework PE Verifier. Version 4.0.30319.18020 Copyright (c) Microsoft Corporation. All rights reserved.

[IL]: Error: [C:\tmp\hello.exe : HelloWorld1.Program::Main][offset 0x00000011] Stack overflow. 1 Error(s) Verifying hello.exe

Why will it not crash in the CLR?

.assembly extern mscorlib {}
.assembly SampleIL {
    .ver 1:0:1:0
}

.class private auto ansi beforefieldinit HelloWorld1.Program
    extends [mscorlib]System.Object
{
    // Methods
    .method private hidebysig static 
        void Main (
            string[] args
        ) cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 13 (0xd)
        .maxstack 1 // **** NOTE THIS LINE *****
        .entrypoint

        IL_0000: nop
        IL_0001: ldstr "hello world"
        IL_0006: call void [mscorlib]System.Console::WriteLine(string)
        IL_000b: nop

        ldc.i4 2
        ldc.i4 2
        add
        call void [mscorlib]System.Console::WriteLine(int32)

        IL_000c: ret
    } // end of method Program::Main

    .method public hidebysig specialname rtspecialname 
        instance void .ctor () cil managed 
    {
        // Method begins at RVA 0x205e
        // Code size 7 (0x7)
        .maxstack 8    

        IL_0000: ldarg.0
        IL_0001: call instance void [mscorlib]System.Object::.ctor()
        IL_0006: ret
    } // end of method Program::.ctor

} // end of class HelloWorld1.Program
1

There are 1 answers

0
John K On BEST ANSWER

Answer derived from the question comments via @RaymondChen

Common Language Infrastructure (CLI)
Partition III
CIL Instruction Set
Final Draft, Apr 2005

1.7.4 Must provide maxstack

[... snip ... ]
[Note: Maxstack is related to analysis of the program, not to the size of the stack at runtime. It does not specify the maximum size in bytes of a stack frame, but rather the number of items that shall be tracked by an analysis tool. end note]