igor-tkachev/bltoolkit — Issue #70: PEVerify complains about assembly generated with AssemblyBuilderHelper
Author: yln
Created: 2011-12-27 15:40:33+00:00
State: open

I experienced strange behavior when using the overload of `AssemblyBuilderHelper.DefineType` which takes a parent type.
When the supplied base type is a user defined type (`Base`) PEVerify cannot load the generated type.

The following example saves two assemblies to disk.

```
public class Base
{
}

internal class Program
{
private static void Main(string[] args)
{
PlainReflection();

BLReflectionHelper();
}

private static void PlainReflection()
{
var assemblyName = new AssemblyName { Name = "Test-PlainReflection" };
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var module = assembly.DefineDynamicModule("Test-Plain-Reflection.dll");

module.DefineType("TestClass", TypeAttributes.Public, typeof(Base)).CreateType();

assembly.Save("Test-Plain-Reflection.dll");
}

private static void BLReflectionHelper()
{
var assmebly = new AssemblyBuilderHelper("Test-BLReflectionHelper.dll");

assmebly.DefineType("TestClass", typeof(Base)).Create();
//assmebly.DefineType("TestClass").Create(); // without the base class the generated assembly peverifys without errors
//assmebly.DefineType("TestClass", typeof(List)).Create(); // also works, the custom base class is the problem

assmebly.Save();
}
}
```

PEVerify gives the following output.

```
C:\ReflectionTest\bin\Debug>peverify Test-Plain-Reflection.dll

Microsoft (R) .NET Framework PE Verifier. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.

All Classes and Methods in Test-Plain-Reflection.dll Verified.

C:\ReflectionTest\bin\Debug>peverify Test-BLReflectionHelper.dll /verbose

Microsoft (R) .NET Framework PE Verifier. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.

[token 0x02000002] Type load failed.
1 Error(s) Verifying Test-BLReflectionHelper.dll
```

I looked at the generated IL, but unfortunately I do not know how to diagnose such errors or where to start (`0x02000002` is the `TypeDef` token for the generated type). - Any hints on this in general?
Also the `AssemblyBuilderHelper` implementation does not do anything too fancy, so I can not imagine where things go wrong.

[ILDASM - MetaInfo](http://pastebin.com/raw.php?i=Ltiit2n0) (plain reflection)
[ILDASM - MetaInfo](http://pastebin.com/raw.php?i=bwbPP4iL) (BLToolkit)

I am using the latest version of BLToolkit from NuGet (4.1.6.) for .NET 4 on Windows XP 32bit.

PS: Thanks for your great work!