I have an assembly with a single module.
I'm iterating over all the methods in this module and wish to delete the 
ones that aren't used. I'm positive that they aren't used, as they're the 
result of an obfuscator adding junk code.

To determine whether a method is used, I iterate all call instructions from 
all methods of all types in the main module and cache the distinct full 
names. Inefficient but so be it.



var assembly = AssemblyDefinition.ReadAssembly(path);
var module = assembly.MainModule;

var calls = module.Types
    .SelectMany(m => m.Methods)
    .Where(m => m.HasBody)
    .SelectMany(m => m.Body.Instructions)
    .Where(m => m.OpCode == OpCodes.Call)
    .Select(i => i.Operand as MethodReference)
    .Select(i => i.FullName)
    .Distinct().ToArray();

I then iterate the methods of all types and see if the method's full name 
is in this list. If it's not, it's not referenced anywhere and should be 
removed.

foreach (var t in module.Types)
{
        var toRemove = new List<MethodDefinition>();

    foreach (var m in t.Methods)
    {
        if (calls.All(c => c != m.FullName))
        {
            toRemove.Add(m);
        }
    }

    foreach (var m in toRemove)
    {
        t.Methods.Remove(m);
    }
}

Seems fine, I see the methods that I would have removed by hand. However, 
when I then go to write the assembly back, I get a vague error.

System.ArgumentException: 'Member 'System.Void Foo(System.Int32)' is 
declared in another module and needs to be imported'

Have I missed something in finding all the method usages? Am I wrong in 
thinking that I don't need to import references since I'm not adding 
anything new?

Thanks in advance

-- 
-- 
--
mono-cecil
--- 
You received this message because you are subscribed to the Google Groups 
"mono-cecil" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/mono-cecil/9764e3d5-21a8-4017-84e4-2eb89f18ec5f%40googlegroups.com.

Reply via email to