This project is read-only.

IL rewriting after code rewriting?

Dec 7, 2012 at 12:52 PM


I use the code model to instrument method bodies via a custom CodeRewriter. Before writing the module back to disk I want to run another instrumentation phase. This time I want to use a ILRewriter - but only for special instructions that reside in a known Block (in the code model).

How would I do that?



Dec 7, 2012 at 5:30 PM

You can do this by using ILocation objects to correlate IL instructions with source locations.

However, I have to ask, why not just instrument the code model?

Dec 7, 2012 at 11:48 PM
Edited Dec 7, 2012 at 11:50 PM

Thanks for pointing this out - I am going to try this.

I want to instrument the metadata model because my instrumentation rules apply to single il instructions. 

An example:

stfld <FieldReference>

Will result in:

<tmpValue> is a local variable of type <FieldReference>.Type
<id> is a id that corresponds to <FieldReference>

stloc <tmpValue>
ldc.i4 <id>
call void [MyAssembly]Logger::StoreField(object, int32)
ldloc <tmpValue>
stfld <FieldReference>

I thought it would be more difficult to realize this rule instrumenting the code model. Am I wrong?

Dec 14, 2012 at 6:36 PM

You can easily do this with the Code Model if you use BlockExpressions. For instance, given:

myField = someExpr; //some pseudo code serialization of the Code Model Assignment.

you'll replace it with a Code Model Block Expression, for which the pseudo code looks something like:

let { var tmpValue = someExpr; [MyAssembly]Logger.StoreField(tmpValue, id); myField = tmpValue; } in tmpValue

Dec 19, 2012 at 7:58 AM

Ok - thanks alot. Thats nice!

I thought that instrumentation in the Code Model would be more difficult because different cases had to be considered: Instrumentation is easy in the CodeModel for the Console.WriteLine(field) statement (let field be an instance field). But it is not allowed to insert instrumentation code (at least in C#) if it is located in an if condition - the instrumentation code must be placed before the whole if block. 

if(field == 0) { Console.WriteLine(field); }

Does the instrumentation of the if condition work with BlockExpression?

(By the way: I only use the local variable tmpValue to unwind the stack because I need to duplicate the pointer to the object whith the field that is read/written. So the assignmend of the local variable can be ommitted in the Code Model.)

Dec 19, 2012 at 8:16 AM

The Code Model is a representation of IL, not C#. Unlike C#, the Code Model can represent any program that can be expressed in IL.