Why Is the .MaxStack Directive Optional in MSIL Code?

后端 未结 2 594
情书的邮戳
情书的邮戳 2021-01-02 00:17

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

相关标签:
2条回答
  • 2021-01-02 00:44

    If I recall correctly, the default stack size is 8 if the statement is omitted.

    0 讨论(0)
  • 2021-01-02 00:45

    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.

    0 讨论(0)
提交回复
热议问题