This project is read-only.

Does ILRewriter adjust .maxstack?

Topics: Metadata Model
Nov 29, 2012 at 2:01 PM
Edited Nov 29, 2012 at 3:23 PM


use a custom ILRewriter to rewrite single operations in method bodies. Now I have a scenario where peverify reports a stack overflow for one of the instrumented methods. The .maxstack value of this method is set to one - but through my instrumentation the stack size growes at least to 3.

I debugged through the ILRewriter.Emit(Operation o) and the ILGenerator but couldn't find code that tries to calculate the needed stack size (I found the code that implements this task in CodeModelToILConverter - but I currently don't use the code model).

So my question ist - do I have to adjust .maxstack on my own? If the answer is yes - where would I do it? (I know that my instrumentation needs new_.maxstack = old_.maxstack + x)




Nov 29, 2012 at 4:05 PM

I just figured out how to adjust the MaxStack value of a MethodBody. However the adjusted value is not implemented in the assembly. The reason is located in ILRewriter.cs, line 122:

public virtual IMethodBody Rewrite(IMethodBody methodBody) {    
.maxStack = methodBody.MaxStack;
// ... this.EmitMethodBody(methodBody); return new ILGeneratorMethodBody(this.Generator, methodBody.LocalsAreZeroed, this.maxStack, methodBody.MethodDefinition, this.localVariables.ToArray(), Enumerable<ITypeDefinition>.Empty); }

If methodBody.MaxStack is changed during EmitMethodBody(methodBody) - the changed value is simply ignored. Is there a particular reason for this? As a 'workaround' I am going to change this behaviour - will it breat anything?

Nov 29, 2012 at 4:53 PM

Hi Jochen

The answer to your first question is "yes, you have to adjust MaxStack yourself". As for your second question, since ILRewriter does not assume that the method body it rewrites is mutable, it provides a protected field that you can update with the adjusted MaxStack value.


Nov 29, 2012 at 7:15 PM

Thanks alot for the quick response. I somehow did not think of setting the protected field...