问题
I am learning assembly language in my spare time. Can anyone explain why .maxstack appears to be optional in this program. I have tried to find the answer online and in my book with no such luck i.e. the program will compile and run with .Maxstack commented out:
//Add.il
//Add Two Numbers
.assembly extern mscorlib {}
.assembly Add
{
.ver 1:0:1:0
}
.module add.exe
.method static void main() cil managed
{
//.maxstack 2
.entrypoint
ldstr "The sum of 50 and 30 is = "
call void [mscorlib]System.Console::Write (string)
ldc.i4.s 50
ldc.i4 30
add
call void [mscorlib]System.Console::Write (int32)
ret
}
I am compiling the program at the command line using the ILASM tool and then running the generated executeable.
回答1:
I think your confusion stems from a misunderstanding of what .maxstack
actually does. It's an easy mistake to make, because it seems like it would cause an error when executing. Surprisingly, that particular directive actually has nothing do with the with stack size at runtime, instead, it is specifically used during code verification.
From Partition III - Section 1.7.4
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 must be tracked by an analysis tool.
The code becomes unverifiable. That same section, notes that any conforming implementation need not support a method with an invalid max stack value. However, it doesn't say that it must not, and quite clearly, the runtime is executing the code. So if it seems to have no effect, why even bother having it?
Believe it or not, by default, the .NET framework runs unverifiable code. It was actually difficult for me to figure out how to enable verification in .NET 4.0, but if you do turn on CAS, your program (with .maxstack 1
) will stop running with
Unhandled Exception: System.InvalidProgramException: Common Language Runtime detected an invalid program. at main()
Keeping this in mind, unverifiable the code cannot run in any environment that doesn't have full trust (generally assemblies from the internet). If that's not important to you, you can let it be an invalid value, and it really won't make a difference. If the code itself is still correct, it will run fine; of course if there is an actually an issue with the IL stack, it will throw an InvalidProgramException
.
回答2:
If I recall correctly, the default stack size is 8 if the statement is omitted.
来源:https://stackoverflow.com/questions/9846022/why-is-the-maxstack-directive-optional-in-msil-code