|
| 1 | +using Microsoft.Diagnostics.NETCore.Client; |
| 2 | +using Microsoft.Diagnostics.Symbols; |
| 3 | +using Microsoft.Diagnostics.Tracing; |
| 4 | +using Microsoft.Diagnostics.Tracing.Etlx; |
| 5 | +using Microsoft.Diagnostics.Tracing.Stacks; |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Diagnostics; |
| 9 | +using System.Diagnostics.Tracing; |
| 10 | +using System.IO; |
| 11 | +using System.Linq; |
| 12 | +using System.Threading.Tasks; |
| 13 | +using System.Windows.Forms; |
| 14 | + |
| 15 | +namespace emstackdump |
| 16 | +{ |
| 17 | + class Program |
| 18 | + { |
| 19 | + static void Main(string[] args) |
| 20 | + { |
| 21 | + IList<string> tempNetTraceFilenames = Array.Empty<string>(); |
| 22 | + IList<string> tempEtlxFilenames = Array.Empty<string>(); |
| 23 | + |
| 24 | + try |
| 25 | + { |
| 26 | + var publishedProcessesPids = DiagnosticsClient.GetPublishedProcesses().ToHashSet(); |
| 27 | + var processIds = Process.GetProcessesByName("MailClient").Select(process => process.Id).Where(id => publishedProcessesPids.Contains(id)).ToList(); |
| 28 | + |
| 29 | + if (processIds.Count == 0) |
| 30 | + { |
| 31 | + processIds = Process.GetProcessesByName("eM Client").Select(process => process.Id).Where(id => publishedProcessesPids.Contains(id)).ToList(); |
| 32 | + } |
| 33 | + |
| 34 | + if (processIds.Count == 0) |
| 35 | + { |
| 36 | + MessageBox.Show("Memory dump not performed, because the process was not found. Ensure the application is running"); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + var tempPath = Path.Combine(Path.GetTempPath(), "em" + Guid.NewGuid().ToString()); |
| 41 | + tempNetTraceFilenames = processIds.Select(id => tempPath + "." + id.ToString() + ".etlx").ToList(); |
| 42 | + var collectionTasks = new List<Task>(); |
| 43 | + for (int i = 0; i < processIds.Count; i++) |
| 44 | + { |
| 45 | + collectionTasks.Add(CollectTrace(processIds[i], tempNetTraceFilenames[i])); |
| 46 | + } |
| 47 | + Task.WaitAll(collectionTasks.ToArray()); |
| 48 | + |
| 49 | + string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "eM Client Stack Dump " + DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss") + ".txt"); |
| 50 | + using var outputFile = new StreamWriter(fileName, false); |
| 51 | + |
| 52 | + // using the generated trace file, symbolocate and compute stacks. |
| 53 | + using var symbolReader = new SymbolReader(System.IO.TextWriter.Null) { SymbolPath = SymbolPath.MicrosoftSymbolServerPath }; |
| 54 | + tempEtlxFilenames = new List<string>(); |
| 55 | + for (int i = 0; i < processIds.Count; i++) |
| 56 | + { |
| 57 | + var tempEtlxFilename = TraceLog.CreateFromEventPipeDataFile(tempNetTraceFilenames[i]); |
| 58 | + tempEtlxFilenames.Add(tempEtlxFilename); |
| 59 | + |
| 60 | + outputFile.WriteLine("-- Process {0} --", processIds[i]); |
| 61 | + |
| 62 | + using (var eventLog = new TraceLog(tempEtlxFilename)) |
| 63 | + { |
| 64 | + var stackSource = new MutableTraceEventStackSource(eventLog) { OnlyManagedCodeStacks = true }; |
| 65 | + var computer = new SampleProfilerThreadTimeComputer(eventLog, symbolReader); |
| 66 | + computer.GenerateThreadTimeStacks(stackSource); |
| 67 | + |
| 68 | + var samplesForThread = new Dictionary<int, List<StackSourceSample>>(); |
| 69 | + |
| 70 | + stackSource.ForEach((sample) => |
| 71 | + { |
| 72 | + var stackIndex = sample.StackIndex; |
| 73 | + while (!stackSource.GetFrameName(stackSource.GetFrameIndex(stackIndex), false).StartsWith("Thread (")) |
| 74 | + stackIndex = stackSource.GetCallerIndex(stackIndex); |
| 75 | + |
| 76 | + // long form for: int.Parse(threadFrame["Thread (".Length..^1)]) |
| 77 | + // Thread id is in the frame name as "Thread (<ID>)" |
| 78 | + string template = "Thread ("; |
| 79 | + string threadFrame = stackSource.GetFrameName(stackSource.GetFrameIndex(stackIndex), false); |
| 80 | + int threadId = int.Parse(threadFrame.Substring(template.Length, threadFrame.Length - (template.Length + 1))); |
| 81 | + |
| 82 | + if (samplesForThread.TryGetValue(threadId, out var samples)) |
| 83 | + { |
| 84 | + samples.Add(sample); |
| 85 | + } |
| 86 | + else |
| 87 | + { |
| 88 | + samplesForThread[threadId] = new List<StackSourceSample>() { sample }; |
| 89 | + } |
| 90 | + }); |
| 91 | + |
| 92 | + // For every thread recorded in our trace, print the first stack |
| 93 | + foreach (var (threadId, samples) in samplesForThread) |
| 94 | + { |
| 95 | + outputFile.WriteLine($"Found {samples.Count} stacks for thread 0x{threadId:X}"); |
| 96 | + PrintStack(outputFile, threadId, samples[0], stackSource); |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + MessageBox.Show(String.Format("Memory dump complete. File location: {0}", fileName)); |
| 102 | + } |
| 103 | + catch (Exception e) |
| 104 | + { |
| 105 | + MessageBox.Show("Memory dump failed because of the following error:\n" + e.Message); |
| 106 | + } |
| 107 | + finally |
| 108 | + { |
| 109 | + foreach (var fileName in tempNetTraceFilenames) |
| 110 | + File.Delete(fileName); |
| 111 | + foreach (var fileName in tempEtlxFilenames) |
| 112 | + File.Delete(fileName); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + static List<EventPipeProvider> providers = new List<EventPipeProvider>() |
| 117 | + { |
| 118 | + new EventPipeProvider("Microsoft-DotNETCore-SampleProfiler", EventLevel.Informational) |
| 119 | + }; |
| 120 | + |
| 121 | + private static async Task CollectTrace(int processId, string tempNetTraceFilename) |
| 122 | + { |
| 123 | + var client = new DiagnosticsClient(processId); |
| 124 | + using var session = client.StartEventPipeSession(providers); |
| 125 | + // collect a *short* trace with stack samples |
| 126 | + // the hidden '--duration' flag can increase the time of this trace in case 10ms |
| 127 | + // is too short in a given environment, e.g., resource constrained systems |
| 128 | + // N.B. - This trace INCLUDES rundown. For sufficiently large applications, it may take non-trivial time to collect |
| 129 | + // the symbol data in rundown. |
| 130 | + using (FileStream fs = File.OpenWrite(tempNetTraceFilename)) |
| 131 | + { |
| 132 | + Task copyTask = session.EventStream.CopyToAsync(fs); |
| 133 | + await Task.Delay(TimeSpan.FromSeconds(5)); |
| 134 | + session.Stop(); |
| 135 | + await copyTask; |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private static void PrintStack(TextWriter output, int threadId, StackSourceSample stackSourceSample, StackSource stackSource) |
| 140 | + { |
| 141 | + output.WriteLine($"Thread (0x{threadId:X}):"); |
| 142 | + var stackIndex = stackSourceSample.StackIndex; |
| 143 | + while (!stackSource.GetFrameName(stackSource.GetFrameIndex(stackIndex), verboseName: false).StartsWith("Thread (")) |
| 144 | + { |
| 145 | + output.WriteLine($" {stackSource.GetFrameName(stackSource.GetFrameIndex(stackIndex), verboseName: false)}" |
| 146 | + .Replace("UNMANAGED_CODE_TIME", "[Native Frames]")); |
| 147 | + stackIndex = stackSource.GetCallerIndex(stackIndex); |
| 148 | + } |
| 149 | + output.WriteLine(); |
| 150 | + } |
| 151 | + } |
| 152 | +} |
0 commit comments