Tagged: clr

Tech talk: CLR Memory Diagnostics

Today’s tech talk we discussed the recent release from Microsoft of ClrMD that lets you attach and debug processes using an exposed API. You used to be able to do this in WinDbg using the SOS plugin, but now they’ve wrapped SOS in a managed dll that you can use to inspect CLR process information. The nice thing about this is you can now automate debugging inspections. It’s now as easy as

int pid = Process.GetProcessesByName("TestApplication")[0].Id;

using (DataTarget dataTarget = DataTarget.AttachToProcess(pid, 5000))
    string dacLocation = dataTarget.ClrVersions[0].TryGetDacLocation();
    ClrRuntime runtime = dataTarget.CreateRuntime(dacLocation);

    ClrHeap heap = runtime.GetHeap();

    foreach (ulong obj in heap.EnumerateObjects())
         ClrType type = heap.GetObjectType(obj);
         ulong size = type.GetSize(obj);
         Console.WriteLine("{0,12:X} {1,8:n0} {2}", obj, size, type.Name);

ClrMD lets you take stack snapshots of running threads, iterate through all objects in the heap and get their values out, show all loaded modules and more. If you combine it with ScriptCSRead more