我在业余时间学习汇编语言。谁能解释为什么 .maxstack 在这个程序中似乎是可选的。我试图在网上和我的书中找到答案,但没有这样的运气,即程序将编译并运行 .Maxstack 注释掉:
//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
}
我正在使用 ILASM 工具在命令行编译程序,然后运行生成的可执行文件。
最佳答案
我认为您的困惑源于对 .maxstack
的误解实际上确实如此。这是一个容易犯的错误,因为它似乎在执行时会导致错误。令人惊讶的是,该特定指令实际上具有 与运行时堆栈大小无关 ,而是专门用于代码验证。
来自第 III 部分 - 第 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.
代码变成无法验证 .同一部分指出,任何符合要求的实现都不需要支持具有无效最大堆栈值的方法。然而,它并不是说它一定不能,而且很明显,运行时正在执行代码。因此,如果它似乎没有效果,为什么还要费心去拥有它呢?
信不信由你,默认情况下,.NET 框架运行无法验证的代码。我实际上很难弄清楚如何在 .NET 4.0 中启用验证,但是如果您打开 CAS,您的程序(带有
.maxstack 1
)将停止运行Unhandled Exception: System.InvalidProgramException: Common Language Runtime detected an invalid program. at main()
记住这一点,无法验证的代码不能在没有完全信任的任何环境中运行(通常是来自互联网的程序集)。如果这对你不重要,你可以让它成为一个无效值,它真的不会有什么不同。如果代码本身仍然正确,它将运行良好;当然,如果 IL 堆栈确实存在问题,它会抛出
InvalidProgramException
.
关于.net - 为什么 .MaxStack 指令在 MSIL 代码中是可选的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9846022/