Find If Allocate - find if a given method or one of it callees will allocate on the GC heap (call new), using mono.cecil to decompile IL

CSharp · Console

/Program.cs

using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Reflection;
using System.Collections.Generic;
using System;
using System.Linq;

namespace FindMemroyAllocations
{
    internal class Program
    {
        public static void DoAlloc(List<int> list)
        {
            foreach (var i in list) // Allocates enumerator
            {
                if (i == 0)
                    break;
            }
        }

        public static bool DoAlloc2()
        {
            string s = "hello" + "goodbye;";
            string s2 = s + "bye"; // Allocates
            return s2.Length > s.Length;
        }

        public static void DoesntAlloc(List<int> list)
        {
            for(int i = 0; i < list.Count; i++)
            {
                if (i == int.MaxValue)
                    break;
            }
        }

        record Data(Dictionary<string, MethodDefinition> nameToMethod, 
            Dictionary<string, bool> methodNameToDoesItAllocate,
            HashSet<string> loadedAssemblies);

        // Read all method definitions from the given assembly, and if it has re-exported
        // types from private framework assemblies, load those too.
        static Data AddMethodDefsFromAssembly(Assembly asm, Data data)
        {
            var asmName = asm.FullName!;
            if (data.loadedAssemblies.Contains(asmName))
                return data;
            data.loadedAssemblies.Add(asmName);
            var assembly = AssemblyDefinition.ReadAssembly(new Uri(asm.GetName().CodeBase!).LocalPath);
            // Some assemblies (e.g. System.Collections) re-export some types (e.g. List<T>) from
            // a private assembly. Find out and load those private assemblies too.
            foreach(var type in assembly.MainModule.ExportedTypes)
            {
                if (type.Scope.Name != asm.GetName().Name)
                {
                    var fullName = ((AssemblyNameReference)type.Scope).FullName;
                    if (!data.loadedAssemblies.Contains(fullName))
                    {
                        var privateAsm = Assembly.Load(fullName);
                        data = AddMethodDefsFromAssembly(privateAsm, data);
                    }
                }
            }

            var combinedDict = new Dictionary<string, MethodDefinition>(
                // Get all methods
                data.nameToMethod.Concat(assembly.MainModule.GetTypes().SelectMany(t => t.Methods)
                // Ignore those which have already been added
                .ExceptBy(data.nameToMethod.Keys, m => m.FullName)
                .ToDictionary(m => m.FullName, m => m)));
            // Replace data with a new data with the new combined dictionary
            return data with { nameToMethod = combinedDict };
        }

        static bool DoesAllocateImpl(Data data, string methodName)
        {
            // Stop if we've already checked this method.
            if (data.methodNameToDoesItAllocate.TryGetValue(methodName, out bool doesItAlloc))
            {
                return doesItAlloc;
            }
            if (data.nameToMethod.TryGetValue(methodName, out MethodDefinition? methodDef) &&
                methodDef.Body != null)
            {
                foreach (var instruction in methodDef.Body.Instructions)
                {
                    if (instruction.OpCode == OpCodes.Newobj || instruction.OpCode == OpCodes.Box)
                    {
                        data.methodNameToDoesItAllocate[methodName] = true;
                        return true;
                    }
                    // A method call - find the method and analyse it too.
                    // BUG: Also handle OpCodes.Calli
                    if (instruction.OpCode == OpCodes.Callvirt || instruction.OpCode == OpCodes.Call)
                    {
                        var memberRef = (MemberReference)instruction.Operand;
                        var scope = memberRef.DeclaringType.Scope as AssemblyNameReference;
                        if (scope != null && !data.loadedAssemblies.Contains(scope.FullName!))
                        {
                            var asm = Assembly.Load(scope.FullName!);
                            data = AddMethodDefsFromAssembly(asm, data);
                        }
                        string fullName = memberRef.Resolve().FullName;
                        if (DoesAllocateImpl(data, fullName))
                            return true;
                    }
                }
            }
            data.methodNameToDoesItAllocate[methodName] = false;
            return false;
        }


        static bool DoesAllocate(string methodName)
        {
            var assembly = AssemblyDefinition.ReadAssembly(
                new Uri(
                    Assembly.GetExecutingAssembly().GetName().CodeBase!).LocalPath);
            var fullMethodName = assembly.MainModule.GetType(typeof(Program).FullName)
                .Methods
                .FirstOrDefault(m => m.Name == methodName)!.FullName;
            var data = AddMethodDefsFromAssembly(Assembly.GetExecutingAssembly(), new Data(
                new Dictionary<string, MethodDefinition>(), new Dictionary<string, bool>(), new HashSet<string>()));
            return DoesAllocateImpl(data, fullMethodName);
        }



        static void Main(string[] args)
        {
            bool doesAllocate = DoesAllocate(nameof(DoAlloc));
            Console.WriteLine($"DoAlloc allocates = {doesAllocate}");

            doesAllocate = DoesAllocate(nameof(DoAlloc2));
            Console.WriteLine($"DoAlloc2 allocates = {doesAllocate}");

            doesAllocate = DoesAllocate(nameof(DoesntAlloc));
            Console.WriteLine($"DoesntAlloc allocates = {doesAllocate}");

            // Fake calls to avoid compiler warnings
            DoAlloc(new List<int>());
            DoesntAlloc(new List<int>());
        }
    }
}
;