This project is read-only.

PeToPE changes mscorlib method references tokens

Topics: PE Writer
Jan 21, 2011 at 9:52 AM

Running the sample project PeToPe results in the new PE having a different method reference byte. I get this picture ( when I run ildasm on HelloWorld.exe and ( is on top), with the ildasm View->Show Bytes option turned on and the differing byte indicated. Is there a way to get the .pe reference byte to match the method reference byte from the original program? 

The original program is targeted to .NET 2.0. 

Jan 21, 2011 at 4:24 PM

PeToPe basically decompiles the original pe file and then compiles it to a new file. The object model that is the intermediate stage abstracts over some things, such as member reference tokens. As a result, these tokens may appear in a different order in the resulting assembly. The new order is just as good as the old one and sometimes better.

Jan 21, 2011 at 7:37 PM

Perhaps some context will help clarify: What I want is to be able to add instrumentation calls to the code (similar to the ILMutator sample), take the resulting IL and pipe it to the .NET Profiling API's SetILFunctionBody. This allows the instrumentation calls without requiring the execution of a different assembly. The issue is that with the different method reference tokens an InvalidProgramException is thrown. It seems the only different references are mscorlib calls. I thought perhaps this resulted from different mscorlib versions.

Jan 21, 2011 at 7:40 PM

Try running peverify on the resulting assembly and see if the (somewhat cryptic) error messages point towards the problem. If you're stuck, see if you can reproduce the problem in a small sample and send it my way for a look.

Jan 23, 2011 at 4:28 AM

Sorry, I see that I did not read the last bit carefully enough. In the case of SetILFunctionBody, you clearly need all tokens to be exactly the same. This is a scenario that is not currently supported by CCI. It would be great to have such support and it should be possible with relatively modest effort, but I have no immediate plans to implement such support myself.

Jan 26, 2011 at 9:13 AM

Hmm, do you have an outline of an approach in mind?

May 10, 2011 at 1:52 AM

If you generate the new code using ILGenerator (either directly or via the mutable CodeModel), then you'll get an iteration of IOperation values that contain metadata references. If you obtained these from the metadata reader, then they will implement IMetadataObjectWithToken. If you now turn this into a byte array yourself (without involving the PeWriter), you can insert the tokens without loss of fidelity.