Remove a Method

Topics: Metadata Model, PE reader, PE Writer
Nov 19, 2009 at 5:53 PM

Hi,

I'm trying to create a tool to remove methods from an assembly given a set of criteria. Let's say in my assembly I have some classes containing methods that are marked with a "RemoveThisMethodAttribute" Custom Attribute. I want to create a simple tool that will load the assembly and remove each of these methods. I can guarantee that there are no callers of these methods in the assembly, as they are for external reference use only.

Is this something I can do with CCI?

I've had a play and the approaches I have tried seem to come up against cases where you can add to or modify items, but not remove them. I've tried creating a copy of the IAssembly in a new Assembly instance and then working through the types in there, but can't seem to modify the types. I also tried creating a MetadataMutator to filter the methods:

        public override IMethodDefinition Visit(IMethodDefinition methodDefinition)
        {
            var removeAttributes = from a in methodDefinition.Attributes
                                       where a.Type.TypeCode == PrimitiveTypeCode.NotPrimitive
                                       let type = a.Type as INamedEntity
                                       where type.Name.Value.Contains("RemoveThisMethodAttribute")
                                       select a;

            if (removeAttributes.Any())
            {
                Console.WriteLine("Removing " + methodDefinition.ToString());
                return null;
            }

            return base.Visit(methodDefinition);
        }
    }

This results in a NullReferenceException during PE writing. Any guidance you could provide as to the right approach for this problem would be great. My alternative is ildasm/ilasm with string munging in the middle which isn't really my favored approach!

Thanks,

Simon.

Coordinator
Nov 19, 2009 at 5:58 PM

Override Visit(List<IMethodDefinition> methodDefinitions) and change it to copy over the list a new list, omitting any methods that have the attribute.

Coordinator
Nov 19, 2009 at 6:01 PM

Also have a look at AttributeHelper.Contains.

Nov 19, 2009 at 6:03 PM

Ah, nice - I'll give that a go.

Thanks!