Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an API for verifying the MSIL of a dynamic assembly at runtime?

When using Reflection.Emit to build an assembly at runtime, I'd like to verify the assembly MSIL before saving to disc. Like PEVerify but at runtime. Is there such an API?

like image 316
Stephen Swensen Avatar asked Sep 03 '11 03:09

Stephen Swensen


2 Answers

It seems that peverify.exe is a front-end to c:\Windows\Microsoft.NET\Framework\v4.0.30319\peverify.dll (or c:\Windows\Microsoft.NET\Framework\v2.0.50727\peverify.dll for CLR 2.0), which is a native DLL (actually, peverify.exe is also native)

I don't see this documented anywhere so it's probably not a public API. You may be able to figure out the exported functions from that DLL using something like Dependency Walker, but I think it would be simpler to just call peverify.exe.

EDIT: anecdotal evidence:

  • In a compiler step, Boo actually calls peverify.exe.
  • Nemerle calls peverify.exe in its tests.
  • Castle.DynamicProxy calls peverify.exe in its tests.
like image 159
Mauricio Scheffer Avatar answered Oct 18 '22 17:10

Mauricio Scheffer


Instead of using PEVerify you could use the ILSpy's decompiler for an in-process solution, as described here: http://www.codeproject.com/Tips/659692/Automated-MSIL-PE-verification-using-ILSpy

A summary of the article is:

  1. Collect the relevant DLLs to reference from your test project, or runtime IL checker in this case
  2. Iterate through the methods to verify using Mono.Cecil
  3. For each method, add it to the AstBuilder defined in ICSharpCode.Decompiler which performs the validation. Eg.
var context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType };
var astBuilder = new AstBuilder(context);
astBuilder.AddMethod(method);

Performance-wise I have not checked which method is faster. Although this method is in-proc it may be slower since the Abstract Syntax Tree is built as the IL is validated (I'll have to setup a performance test to check this theory).

I found the ILSpy decompiler to be more reliable than PEVerify as pointed out in the above article, in one instance PEVerify declared one assembly to be valid, while ILSpy correctly gave a beautiful stack trace indicating my error in generation.

like image 2
ilen Avatar answered Oct 18 '22 19:10

ilen