jbevain / cecil

Cecil is a library to inspect, modify and create .NET programs and libraries.
MIT License
2.77k stars 630 forks source link

Create type in separate netmodule not supported #818

Open kant2002 opened 2 years ago

kant2002 commented 2 years ago

Take a look at this snippet

using Mono.Cecil;

var fooModule = ModuleDefinition.CreateModule("Foo", ModuleKind.NetModule);
var foo = new TypeDefinition("", "Foo", 0, fooModule.TypeSystem.Object);
fooModule.Types.Add(foo);

var mainModule = ModuleDefinition.CreateModule("Main", ModuleKind.NetModule);
mainModule.ModuleReferences.Add(fooModule);
var program = new TypeDefinition("", "Program", TypeAttributes.Class, mainModule.TypeSystem.Object);
program.Fields.Add(new FieldDefinition("foo", FieldAttributes.Static, mainModule.ImportReference(foo)));
mainModule.Types.Add(program);

Right now Cecil crashes with

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Mono.Cecil.DefaultMetadataImporter.ImportScope(IMetadataScope scope)
   at Mono.Cecil.DefaultMetadataImporter.ImportScope(TypeReference type)
   at Mono.Cecil.DefaultMetadataImporter.ImportType(TypeReference type, ImportGenericContext context)
   at Mono.Cecil.DefaultMetadataImporter.ImportReference(TypeReference type, IGenericParameterProvider context)
   at Mono.Cecil.ModuleDefinition.ImportReference(TypeReference type, IGenericParameterProvider context)
   at Mono.Cecil.ModuleDefinition.ImportReference(TypeReference type)

This fails at this line https://github.com/jbevain/cecil/blob/7b8ee049a151204997eecf587c69acc2f67c8405/Mono.Cecil/Import.cs#L524 when attempt to get Name from Assembly which is not defined in this case.

So apparently Cecil not very well supports creation of netmodules.