dotnet / diagnostics

This repository contains the source code for various .NET Core runtime diagnostic tools and documents.
MIT License
1.18k stars 354 forks source link

Managed memory dump with API #2591

Closed kRaBby closed 3 years ago

kRaBby commented 3 years ago

The general question is: how can I create a managed memory dump with Microsoft.Diagnostics.NETCore.Client API? Ideally which can be opened with PerfView? Can I create .gcdump like in dotnet-gcdump tool? Or maybe .dmp like in dotnet-dump tool. If yes then how can I do that?

mikem8361 commented 3 years ago

/cc: @dotnet/dotnet-diag

josalem commented 3 years ago

@kRaBby it's worth pointing out that the gcdump format does not actually contain the memory from the heap. Instead, it contains a graph that represents the state of the heap at a given point in time. Each node represents an object on the heap and each edge represents a rooting relationship. You can open the gcdump format in PerfView for viewing metadata and structure of the heap, but you cannot inspect the objects themselves.

As for programmatically making one, I don't believe we include the APIs in Microsoft.Diagnostics.NETCore.Client since it requires intimate knowledge of how the runtime sends a specific sequence of events during a GC. The code for collecting one is contained in the dotnet-gcdump tool and is open source.

Another way to collect the same information as a gcdump plus be able to inspect individual objects would be to collect a dump (easily doable via Microsoft.Diagnostics.NETCore.Client) and use something like ClrMD to programmatically collect heapstats and inspect objects.

noahfalk commented 3 years ago

Or maybe *.dmp like in dotnet-dump tool.

Reference the Microsoft.Diagnostics.NetCore.Client nuget package and use this example code:

using Microsoft.Diagnostics.NetCore.Client;

public void TriggerCoreDump(int processId)
{
    var client = new DiagnosticsClient(processId);
    client.WriteDump(DumpType.Normal);
}

dotnet-dump is an open source tool and you can see its full source here

Can I create *.gcdump like in dotnet-gcdump tool?

As @josalem mentioned this one is more complex and there is no quick API call that will do it, but you can see how dotnet-gcdump does it by examining the code here. Again since all the source is OSS you are free to reuse it as long as you comply with the MIT license which is usually an easy bar to clear.

Hope that helps!