在.net堆中查找类型的实例数据

时间:2015-05-05 20:39:16

标签: c# .net clrmd

假设我有两个类Foo和Bar如下

public class Foo
{
    private Bar _bar;
    private string _whatever = "whatever";
    public Foo()
    {
        _bar = new Bar();
    }

    public Bar TheBar
        {
            get
            {
                return _bar;
            }

        }
}

public class Bar
{
    public string Name { get; set; }
}

我有一个应用程序附加到正在使用这些类的进程。我想在.NET堆中看到所有Foo类型的实例并检查TheBar.Name属性或_whatever all of all Foo实例存在于.NET堆中。我可以找到类型,但我不知道如何获取实例并查看其属性。有什么想法吗?

using (DataTarget target = DataTarget.AttachToProcess(processId, 30000))
{
    string dacLocation = target.ClrVersions[0].TryGetDacLocation();
    ClrRuntime runtime = target.CreateRuntime(dacLocation);

    if (runtime != null)
    {
        ClrHeap heap = runtime.GetHeap();
        foreach (ulong obj in heap.EnumerateObjects())
        {
            ClrType type = heap.GetObjectType(obj);
            if (type.Name.Compare("Foo") == 0 )
            {
                // I would like to see value of TheBar.Name property or _whatever field of all instances of Foo type in the heap. How can I do it?
            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

我认为您不能直接获取属性值,因为这需要您运行代码,目标可能甚至不是进程而是转储文件。

您绝对可以获取对象的字段及其值。 ClrType有一个Fields属性,可用于循环遍历字段。然后,您可以为HasSimpleValue为true的字段调用GetFieldValue。

一个简单的例子:

private static void PrintFieldsForType(ClrRuntime runtime, string targetType)
{
    ClrHeap heap = runtime.GetHeap();
    foreach (var ptr in heap.EnumerateObjects())
    {
        ClrType type = heap.GetObjectType(ptr);
        if (type.Name == targetType)
        {
            foreach(var field in type.Fields)
            {
                if (field.HasSimpleValue)
                {
                    object value = field.GetFieldValue(ptr);
                    Console.WriteLine("{0} ({1}) = {2}", field.Name, field.Type.Name, value);
                }
                else
                {
                    Console.WriteLine("{0} ({1})", field.Name, field.Type.Name);
                }
            }
        }
    }
}

因此,您可以查找具有“名称”,“_名称”或类似内容的字段。如果它是自动实现的属性,则名称将类似于<Name>k__BackingField

您的场景有点复杂,因为您想要进入另一个对象。为此,我们可以递归检查字段。但请注意,在一般情况下,您需要跟踪您访问过的对象,这样您就无法无限期地递归。

以下是一个更适合此的示例:

private static void PrintFieldsForType(ClrRuntime runtime, TextWriter writer, string targetType)
{
    ClrHeap heap = runtime.GetHeap();
    foreach (var ptr in heap.EnumerateObjects())
    {
        ClrType type = heap.GetObjectType(ptr);
        if (type.Name == targetType)
        {
            writer.WriteLine("{0}:", targetType);
            PrintFields(type, writer, ptr, 0);
        }
    }
}

private static void PrintFields(ClrType type, TextWriter writer, ulong ptr, int indentLevel)
{
    string indent = new string(' ', indentLevel * 4);
    foreach (var field in type.Fields)
    {
        writer.Write(indent);
        if (field.IsObjectReference() && field.Type.Name != "System.String")
        {
            writer.WriteLine("{0} ({1})", field.Name, field.Type.Name);
            ulong nextPtr = (ulong)field.GetFieldValue(ptr);
            PrintFields(field.Type, writer, nextPtr, indentLevel + 1);
        }
        else if (field.HasSimpleValue)
        {
            object value = field.GetFieldValue(ptr);
            writer.WriteLine("{0} ({1}) = {2}", field.Name, field.Type.Name, value);
        }
        else
        {
            writer.WriteLine("{0} ({1})", field.Name, field.Type.Name);
        }
    }
}

答案 1 :(得分:1)

以下是使用ClrMD.Extensions在LINQPad中执行此操作的方法:

var session = ClrMDSession.AttachToProcess(processId);
session.EnumerateClrObjects("*Foo").Dump(depth:3);

答案 2 :(得分:-2)

我不知道是否可以以这种方式查询堆。 但一个简单的解决方法是做这样的事情:

public class Foo
{
    public static List<WeakReference<Foo>> allInstances = new List<WeakReference<Foo>>();

    public Foo()
    {
        allInstances.Add(new WeakReference<Foo>(this));
    }
}

确保在WeakReference中包装,这样你的集合就不会将它们保留在堆中,直到进程结束。