internal void ProcessStop(ProcessTraceData data) { if (CommandLine.Length == 0) { CommandLine = data.CommandLine; } ImageFileName = data.ImageFileName; // Always overwrite as we might have guessed via the image loads if (ParentID == 0 && data.ParentID != 0) { ParentID = data.ParentID; } if (data.Opcode != TraceEventOpcode.DataCollectionStop) { Debug.Assert(data.Opcode == TraceEventOpcode.Stop); // Only set the exit code if it really is a process exit (not a DCStop). if (data.Opcode == TraceEventOpcode.Stop) { ExitStatus = data.ExitStatus; } endTimeQPC = data.TimeStampQPC; } }
internal void CleanupOldProcesses(ProcessTraceData data) { // check processes if they are outside of the requested lifetime and remove them // not relying on the process/end event since it is not always the last event int index = 0; while (index < processesByPID.Count) { var process = processesByPID[index]; System.Diagnostics.Debug.Assert(process != null); // if the process has not yet received a stop event, then continue if (!process.ExitStatus.HasValue) { index++; continue; } // if a process has had an event within the last DataLifetime msec, then keep it if (process.EndTimeRelativeMsec >= (data.TimeStampRelativeMSec - source.DataLifetimeMsec)) { index++; } else { // remove from processesByPID - this is a shift copy operation, ugh processesByPID.RemoveRange(index, 1); // remove this process from the stream and return this processIndex back to rotation processes[(int)process.ProcessIndex] = null; // do not advance index, since we should inspect the one that was shifted into this spot } } }
private void ProcessStart(ProcessTraceData args) { if (_currentProcesses.Contains(args.ParentID)) { _currentProcesses.Add(args.ProcessID); } }
private void OnProcessStart(ProcessTraceData obj) { if (obj.ParentID == ProcessId || ChildrenProcessesIds.Contains(obj.ParentID)) { ChildrenProcessesIds.Add(obj.ProcessID); } }
/// <summary> /// /// </summary> /// <param name="data"></param> public void LogEvent(ProcessTraceData data) { //--------- // Filter event data // Not written yet.. //---------- //----------------- // Log Process/Stop/Start event //using (EventLogWriter writer = new EventLogWriter(_processLogName)) //{ // LogRow text = new LogRow(); // text.Add(data.TimeStamp.ToString()); // text.Add(data.EventName); // text.Add(data.ProcessID.ToString()); // text.Add(data.ProcessName); // text.Add(data.CommandLine); // text.Add(data.ImageFileName); // writer.WriteRow(text); //} LogRow text = new LogRow(); _processWriter.WriteHeader(data, text); text.Add(data.CommandLine); text.Add(data.ImageFileName); _processWriter.WriteRow(text); }
private static void Kernel_ProcessStop(ProcessTraceData traceData) { if (traceData.ProcessName == "dotnet") { // this is not firing Console.WriteLine("dotnet process stop"); } }
private static void Kernel_ProcessStart(ProcessTraceData traceData) { if (traceData.ProcessName == "dotnet") { _currentProfileSample = new ProfileSample(); _profileSamples.Add(_currentProfileSample); _currentProfileSample.ProcessStart_TimeStampRelativeMSec = traceData.TimeStampRelativeMSec; } }
private void HandleProcessStart(ProcessTraceData data) { if (data.ParentID == pid) { traceOutput.WriteLine($"{data.TimeStampRelativeMSec:0.0000} ({data.ProcessID}.{data.ThreadID}) {data.EventName} " + $"{data.ProcessID} '{data.CommandLine}'"); noOfChildProcessesStarted++; } }
private void HandleProcessStart(ProcessTraceData data) { if (data.ParentID == pid) { traceOutput.Write(data.TimeStampRelativeMSec, data.ProcessID, data.ThreadID, data.EventName, $"{data.ProcessID} '{data.CommandLine}'"); actionToPerformWhenNewProcessIsCreated(data.ProcessID); } }
// #ProcessHandlersCalledFromTraceLog // // called from TraceLog.CopyRawEvents internal void ProcessStart(ProcessTraceData data) { if (data.Opcode == TraceEventOpcode.DataCollectionStart) { } else { Debug.Assert(data.Opcode == TraceEventOpcode.Start); Debug.Assert(endTimeQPC == long.MaxValue); // We would create a new Process record otherwise } CommandLine = data.CommandLine; ImageFileName = data.ImageFileName; ParentID = data.ParentID; }
/// <summary> /// Calculate process duration and fire an event when a process did terminate /// </summary> /// <param name="obj"></param> private void Kernel_ProcessStop(ProcessTraceData obj) { ProcessTraceData start; for (int i = myProcessStartEvents.Count - 1; i >= 0; i--) { start = myProcessStartEvents[i]; if (obj.ProcessID == start.ProcessID && obj.CommandLine == start.CommandLine) { OnProcessEndedWithDuration?.Invoke(obj, obj.TimeStamp - start.TimeStamp); break; } } }
internal void ProcessStop(ProcessTraceData data) { // handle process stop and fire stop event var process = data.Process(); process.ProcessStop(data); if (OnProcessStop != null) { OnProcessStop(process); } // if there is a lifetime policy, cleanup old processes if (source.DataLifetimeEnabled()) { CleanupOldProcesses(data); } }
private static void Kernel_ProcessStart(ProcessTraceData obj) { try { Process proc = Process.GetProcessById(obj.ProcessID); foreach (string chromePath in ChromeExeFilePaths) { if (chromePath.Equals(proc.MainModule.FileName)) { Console.WriteLine("Injecting into " + proc.Id); Injector.Inject(proc); break; } } } catch (Exception e) { // Ignore some rare errors (often occurr for very short lived processes) Console.WriteLine(e.Message); } }
private void Kernel_ProcessStart(ProcessTraceData processInfo) { if (processInfo.Opcode == Microsoft.Diagnostics.Tracing.TraceEventOpcode.Start) { ProcessInformation startedProcess = new ProcessInformation() { CommandLine = processInfo.CommandLine, ImageFileName = processInfo.ImageFileName, ProcessID = processInfo.ProcessID, SessionID = processInfo.SessionID, CreateTime = processInfo.TimeStamp, }; SecurityIdentifier sid = LsaLogonSessions.LogonSessions.GetSidForSessionId(startedProcess.SessionID); if (sid != null) { startedProcess.UserSIDString = sid.Value; } processList.Add(startedProcess); } }
private void OnProcessStart(ProcessTraceData data) { // not supported for Linux //Console.WriteLine($"+ {data.ImageFileName}"); //_processes.Names[data.ProcessID] = data.ImageFileName; }
private static void KernelOnProcessStop(ProcessTraceData data) { Console.WriteLine($"[{data.ProcessName}] Ending PID {data.ProcessID}"); }
private void ProcessStop(ProcessTraceData args) { _currentProcesses.Remove(args.ProcessID); }
internal ProcessTraceEventViewModel(TraceEvent evt) { ProcessData = (ProcessTraceData)evt; Debug.Assert(ProcessData != null); }
static int Main(string[] args) { bool bNetConnect = false, bNetTransfer = false, bProcess = false, bThread = false, bImageLoad = false; bool bDns = false, bSysmon = false, bRegistry = false, bFile = false; if (args.Length == 0) { Console.WriteLine("\nUsage: ETWMonitor [net_connect | net_transfer | process | thread | imageload | memory | registry | dns | sysmon]\n"); Console.WriteLine("net_connect : Show new TCP connections"); Console.WriteLine("net_transfer : Show network transfers"); Console.WriteLine("process : Show process creations and exits"); Console.WriteLine("thread : Show suspicious thread creation (cross-process)"); Console.WriteLine("imageload : Show image loading"); Console.WriteLine("file : Show file activity"); Console.WriteLine("registry : Show registry details"); Console.WriteLine("dns : Show DNS requests"); Console.WriteLine("sysmon : Show entries from Sysmon"); return(1); } if (args[0] == "net_connect") { Console.WriteLine("\nShowing new network connections"); bNetConnect = true; } else if (args[0] == "net_transfer") { Console.WriteLine("\nShowing network transfers"); bNetTransfer = true; } else if (args[0] == "process") { Console.WriteLine("\nShowing process creation and exits"); bProcess = true; } else if (args[0] == "thread") { Console.WriteLine("\nShowing suspicious thread creations (cross-process)"); bThread = true; } else if (args[0] == "imageload") { Console.WriteLine("\nShowing image loads"); bImageLoad = true; } else if (args[0] == "file") { Console.WriteLine("\nShowing file system activity"); bFile = true; } else if (args[0] == "registry") { Console.WriteLine("\nShowing registry details"); bRegistry = true; } else if (args[0] == "dns") { Console.WriteLine("\nShowing DNS requests"); bDns = true; } else if (args[0] == "sysmon") { Console.WriteLine("\nShowing Sysmon entries"); bSysmon = true; } else { Console.WriteLine("\nInvalid option"); return(1); } // Today you have to be Admin to turn on ETW events (anyone can write ETW events). if (!(TraceEventSession.IsElevated() ?? false)) { Console.WriteLine("To turn on ETW events you need to be Administrator, please run from an Admin process."); return(-1); } var sessionName = ""; if (bNetConnect) { sessionName = "NetConnectSession"; } else if (bNetTransfer) { sessionName = "NetTransferSession"; } else if (bProcess) { sessionName = "ProcessSession"; } else if (bThread) { sessionName = "ThreadSession"; } else if (bImageLoad) { sessionName = "ImageLoadSession"; } else if (bFile) { sessionName = "FileSession"; } else if (bRegistry) { sessionName = "RegistrySession"; } else if (bDns) { sessionName = "DnsSession"; } else if (bSysmon) { sessionName = "SysmonSession"; } else { Console.WriteLine("Error"); return(-1); } using (var session = new TraceEventSession(sessionName, null)) // the null second parameter means 'real time session' { session.StopOnDispose = true; Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { session.Dispose(); }; // prepare to read from the session, connect the ETWTraceEventSource to the session using (var source = new ETWTraceEventSource(sessionName, TraceEventSourceType.Session)) { Action <TraceEvent> action = delegate(TraceEvent data) { var taskName = data.TaskName; var EventName = data.EventName; if (bProcess) { if (EventName == "Process/DCStart" || EventName == "Process/Start") { ProcessTraceData startprocdata = (ProcessTraceData)data; string exe = (string)data.PayloadByName("ImageFileName"); Console.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + EventName); Console.Write(" PPID: " + startprocdata.ParentID.ToString() + " PID: " + startprocdata.ProcessID.ToString()); Console.Write(" Name: " + exe); Process PName = GetProcByID2(startprocdata.ParentID); if (PName != null) { Console.Write(" ParentName: " + PName.ProcessName); } Console.WriteLine(" CommandLine: " + startprocdata.CommandLine); } else if (EventName == "Process/End") { ProcessTraceData exitprocdata = (ProcessTraceData)data; string exe = (string)data.PayloadByName("ImageFileName"); Console.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + EventName); Console.WriteLine(" PPID: " + exitprocdata.ParentID.ToString() + " PID: " + exitprocdata.ProcessID.ToString() + " " + exe); } } else if (bNetConnect) { if (taskName == "TcpRequestConnect") { int threadID = data.ThreadID; int processID = data.ProcessID; byte[] local_addr = (byte[])data.PayloadByName("LocalAddress"); byte[] remote_addr = (byte[])data.PayloadByName("RemoteAddress"); if (local_addr == null || remote_addr == null) { Console.WriteLine("Null addr!"); } // First two bytes are address family: 2 for ipv4, 10 for ipv6 // Next two bytes are the port var family = new byte[2]; family[0] = local_addr[0]; family[1] = local_addr[1]; ushort family_nr = BitConverter.ToUInt16(family, 0); if (family_nr == 2) { var local_port = new byte[2]; var remote_port = new byte[2]; local_port[0] = local_addr[2]; local_port[1] = local_addr[3]; Array.Reverse(local_port); // Need to reverse port remote_port[0] = remote_addr[2]; remote_port[1] = remote_addr[3]; Array.Reverse(remote_port); // Need to reverse port ushort local_port_nr = BitConverter.ToUInt16(local_port, 0); ushort remote_port_nr = BitConverter.ToUInt16(remote_port, 0); Process proc; string processname = "<not found>"; if (processID > 0) { proc = GetProcByID(processID); if (proc != null) { processname = proc.MainModule.ModuleName; } } Console.Write(data.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss") + " " + taskName + " PID: " + processID); int parentid = GetParentProcessID(processID); if (parentid != 0) { Console.Write(" PPID: " + parentid); } else { Console.Write(" PPID: (null)"); } Console.Write(" TID: " + threadID + " Name: " + processname); proc = GetProcByID(parentid); if (proc != null) { Console.Write(" Parent Name: " + proc.ProcessName); } else { Console.Write(" Parent Name: (null)"); } string local_ip = local_addr[4] + "." + local_addr[5] + "." + local_addr[6] + "." + local_addr[7]; string remote_ip = remote_addr[4] + "." + remote_addr[5] + "." + remote_addr[6] + "." + remote_addr[7]; Console.Write(" " + local_ip + ":" + local_port_nr + "->"); Console.WriteLine(remote_ip + ":" + remote_port_nr + " "); } else if (family_nr == 0x10) { Console.WriteLine("IPV6"); } } } else if (bNetTransfer) { if (EventName == "TcpIp/Send" || EventName == "TcpIp/Recv") { Console.Write(data.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss") + " " + EventName + " PID: " + data.ProcessID); Process processname; processname = GetProcByID(data.ProcessID); if (processname != null) { Console.Write(" Name: " + processname.ProcessName); } else { Console.Write(" Name: (null)"); } IPAddress saddr = (IPAddress)data.PayloadByName("saddr"); IPAddress daddr = (IPAddress)data.PayloadByName("daddr"); int sport = (int)data.PayloadByName("sport"); int dport = (int)data.PayloadByName("dport"); int size = (int)data.PayloadByName("size"); Console.Write(" Src: " + saddr.ToString() + ":" + sport + " Dst: " + daddr.ToString() + ":" + dport); Console.WriteLine(" Size: " + size); } } else if (bThread) // try to catch remote thread injections only { if (taskName == "ThreadStart") { int destProcessID = (int)data.PayloadByName("ProcessID"); int parentid; Process processname; if (data.ProcessID != destProcessID && data.ProcessID != 4) { // check if destpid is not a child of srcpid, otherwise we have a problem! // check the parentpid of srcpid int destThreadID = (int)data.PayloadByName("ThreadID"); int srcThreadID = data.ThreadID; parentid = GetParentProcessID(destProcessID); if (parentid != 0 && parentid != data.ProcessID) { Console.Write(data.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss") + " POSSIBLE THREAD INJECTION: "); Console.Write(taskName + " TID: " + destThreadID + " SrcTID: " + srcThreadID + " SrcPID: " + data.ProcessID); Console.Write(" DestPID: " + destProcessID); processname = GetProcByID(data.ProcessID); if (processname != null) { Console.Write(" SrcName: " + processname.ProcessName); } else { Console.Write(" SrcName: (null)"); } processname = GetProcByID(destProcessID); if (processname != null) { Console.WriteLine(" DestName: " + processname.ProcessName); } else { Console.WriteLine(" DestName: (null)"); } Console.WriteLine("\nDetailed information:\n" + data.ToString()); } } } } else if (bImageLoad) { if (EventName == "Image/DCStart" || EventName == "Image/Load" || EventName == "Image/Unload") { int pid = (int)data.ProcessID; Console.Write(data.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss ") + EventName); Console.Write(" PID: " + pid); Process processname; processname = GetProcByID(pid); if (processname != null) { Console.Write(" Name: " + processname.ProcessName); } else { Console.Write(" Name: (null)"); } string filename = (string)data.PayloadByName("FileName"); Console.WriteLine(" FileName: " + filename); } } else if (bFile) { if (EventName == "CreateNewFile" || EventName == "DeletePath" || EventName == "NameDelete") { int pid = (int)data.ProcessID; Console.Write(data.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss ") + EventName); Console.Write(" PID: " + pid); Process processname; processname = GetProcByID(pid); if (processname != null) { Console.Write(" Name: " + processname.ProcessName); } else { Console.Write(" Name: (null)"); } string filename = ""; if (EventName == "DeletePath") { filename = (string)data.PayloadByName("FilePath"); } else { filename = (string)data.PayloadByName("FileName"); } Console.WriteLine(" File: " + filename); } } else if (bRegistry) { if (EventName == "EventID(1)/CreateKey" || EventName == "EventID(5)/SetValueKey" || EventName == "EventID(3)/DeleteKey" || EventName == "EventID(6)/DeleteValueKey") { int pid = (int)data.ProcessID; Console.Write(data.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss ") + EventName); Console.Write(" PID: " + pid); Process processname; processname = GetProcByID(pid); if (processname != null) { Console.Write(" Name: " + processname.ProcessName); } else { Console.Write(" Name: (null)"); } if (EventName == "EventID(1)/CreateKey") { string RelativeName = (string)data.PayloadByName("RelativeName"); int status = (int)data.PayloadByName("Status"); Console.WriteLine(" Status: " + status + " RelativeName: " + RelativeName); } else if (EventName == "EventID(3)/DeleteKey") { int status = (int)data.PayloadByName("Status"); Console.WriteLine(" Status: " + status); } else if (EventName == "EventID(5)/SetValueKey") { string ValueName = (string)data.PayloadByName("ValueName"); int status = (int)data.PayloadByName("Status"); Console.WriteLine(" Status: " + status + " ValueName: " + ValueName); } else if (EventName == "EventID(6)/DeleteValueKey") { string ValueName = (string)data.PayloadByName("ValueName"); int status = (int)data.PayloadByName("Status"); Console.WriteLine(" Status: " + status + " ValueName: " + ValueName); } } } else if (bDns) { int pid = (int)data.ProcessID; Console.Write(data.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss ") + EventName); Console.Write(" PID: " + pid); Process processname; processname = GetProcByID(pid); if (processname != null) { Console.Write(" Name: " + processname.ProcessName); } else { Console.Write(" Name: (null)"); } string QueryName = (string)data.PayloadByName("QueryName"); Console.WriteLine(" QueryName: " + QueryName); } else if (bSysmon) { Console.WriteLine(data.ToString()); } }; // You can also simply use 'logman query providers' to find out the GUID yourself and wire it in. Guid processProviderGuid; if (bProcess) { session.EnableKernelProvider(KernelTraceEventParser.Keywords.Process); } else if (bNetConnect) { processProviderGuid = TraceEventSession.GetProviderByName("Microsoft-Windows-TCPIP"); session.EnableProvider(processProviderGuid, TraceEventLevel.Informational, 0x80); // ut:TcpipDiagnosis seems to do the job } else if (bNetTransfer) { session.EnableKernelProvider(KernelTraceEventParser.Keywords.NetworkTCPIP); } else if (bThread) { processProviderGuid = TraceEventSession.GetProviderByName("Microsoft-Windows-Kernel-Process"); session.EnableProvider(processProviderGuid, TraceEventLevel.Informational, 0x20); // WINEVENT_KEYWORD_THREAD } else if (bImageLoad) { session.EnableKernelProvider(KernelTraceEventParser.Keywords.ImageLoad); } else if (bFile) { processProviderGuid = TraceEventSession.GetProviderByName("Microsoft-Windows-Kernel-File"); session.EnableProvider(processProviderGuid, TraceEventLevel.Informational, 0x0000000000001410); // KERNEL_FILE_KEYWORD_CREATE_NEW_FILE, KERNEL_FILE_KEYWORD_DELETE_PATH, KERNEL_FILE_KEYWORD_FILENAME } else if (bRegistry) { processProviderGuid = TraceEventSession.GetProviderByName("Microsoft-Windows-Kernel-Registry"); session.EnableProvider(processProviderGuid, TraceEventLevel.Informational, 0x0000000000005300); // SetValueKey, CreateKey, DeleteKey, DeleteValueKey } else if (bDns) { processProviderGuid = TraceEventSession.GetProviderByName("Microsoft-Windows-DNS-Client"); session.EnableProvider(processProviderGuid, TraceEventLevel.Informational, 0x8000000000000000); // } else if (bSysmon) { processProviderGuid = TraceEventSession.GetProviderByName("Microsoft-Windows-Sysmon"); session.EnableProvider(processProviderGuid, TraceEventLevel.Informational, 0x8000000000000000); // KERNEL_MEM_KEYWORD_MEMINFO } else { Console.WriteLine("Error"); return(-1); } // We use different parsers depending on the events. For TCP/IP stuff we need to // use another since we want to register not only ProcessID but also ThreadID for each event if (bNetConnect || bThread || bFile || bRegistry || bDns || bSysmon) { // Hook up the parser that knows about Any EventSources regsitered with windows. (e.g. the OS ones). var registeredParser = new RegisteredTraceEventParser(source); registeredParser.All += action; } else { // Hook up the parser that knows about kernel traces var KernelParser = new KernelTraceEventParser(source); KernelParser.All += action; } Console.WriteLine("Starting Listening for events"); // go into a loop processing events can calling the callbacks. Because this is live data (not from a file) // processing never completes by itself, but only because someone called 'source.Close()'. source.Process(); Console.WriteLine(); Console.WriteLine("Stopping Listening for events"); } } return(0); }
internal ProcessTraceEventViewModel(TraceEventDataViewModel root) : base(root.Data, root.Type) { ProcessData = (ProcessTraceData)root.Data; Debug.Assert(ProcessData != null); }
private static void _processStart(ProcessTraceData pData) { Console.WriteLine("Process başladı:\tProcessID: {0}\tProcess ParentID: {1}\tProcessName: {2}\tKomut Satırı: {3}", pData.ProcessID, pData.ParentID, pData.ProcessName, pData.CommandLine); }
private void OnProcessDCStart(ProcessTraceData obj) { var data = (ProcessTraceData)obj.Clone(); ProcessTrace?.Invoke(data, EventType.ProcessExists); }
private void OnProcessStart(ProcessTraceData obj) { ProcessTrace?.Invoke((ProcessTraceData)obj.Clone(), EventType.ProcessStart); }
private void ProcessStopped(ProcessTraceData obj) { }
private void ProcessStarted(ProcessTraceData obj) { }
internal ProcessTraceEventViewModel(TraceEventDataViewModel evt) : base(evt.Data, evt.Type, evt.Details) { ProcessData = (ProcessTraceData)evt.Data; Debug.Assert(ProcessData != null); }
private static void KernelOnProcessStart(ProcessTraceData data) { Console.WriteLine($"[{data.ProcessName}] Starting {data.CommandLine} as PID {data.ProcessID}"); }
private void ProcessStart(ProcessTraceData args) { if (_currentProcesses.Contains(args.ParentID)) _currentProcesses.Add(args.ProcessID); }
public static void Main(string[] args) { string traceFile = args[0]; string benchmarkName = "dotnet"; int benchmarkPid = -2; Dictionary <string, uint> allEventCounts = new Dictionary <string, uint>(); Dictionary <string, uint> eventCounts = new Dictionary <string, uint>(); Dictionary <string, uint> processCounts = new Dictionary <string, uint>(); using (var source = new ETWTraceEventSource(traceFile)) { source.Kernel.All += delegate(TraceEvent data) { if (allEventCounts.ContainsKey(data.EventName)) { allEventCounts[data.EventName]++; } else { allEventCounts[data.EventName] = 1; } if (data.ProcessID == benchmarkPid) { if (eventCounts.ContainsKey(data.EventName)) { eventCounts[data.EventName]++; } else { eventCounts[data.EventName] = 1; } } switch (data.EventName) { case "Process/Start": case "Process/DCStart": { // Process was running when tracing started (DCStart) // or started when tracing was running (Start) ProcessTraceData pdata = (ProcessTraceData)data; if (String.Equals(pdata.ProcessName, benchmarkName, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Found process [{0}] {1}: {2}", pdata.ProcessID, pdata.ProcessName, pdata.CommandLine); benchmarkPid = pdata.ProcessID; } else { // Console.WriteLine("Ignoring events from process {0}", pdata.ProcessName); } break; } case "Image/DCStart": { ImageLoadTraceData imageLoadTraceData = (ImageLoadTraceData)data; if (data.ProcessID == 0) { string fileName = imageLoadTraceData.FileName; ulong imageBase = imageLoadTraceData.ImageBase; int imageSize = imageLoadTraceData.ImageSize; string fullName = fileName + "@" + imageBase.ToString(); if (!ImageMap.ContainsKey(fullName)) { ImageInfo imageInfo = new ImageInfo(Path.GetFileName(fileName), imageBase, imageSize); ImageMap.Add(fullName, imageInfo); } } break; } case "Image/Load": { ImageLoadTraceData imageLoadTraceData = (ImageLoadTraceData)data; if (imageLoadTraceData.ProcessID == benchmarkPid) { string fileName = imageLoadTraceData.FileName; ulong imageBase = imageLoadTraceData.ImageBase; int imageSize = imageLoadTraceData.ImageSize; // Suppress ngen images here, otherwise we lose visibility // into ngen methods... if (fileName.Contains(".ni.")) { break; } string fullName = fileName + "@" + imageBase.ToString(); if (!ImageMap.ContainsKey(fullName)) { ImageInfo imageInfo = new ImageInfo(Path.GetFileName(fileName), imageBase, imageSize); ImageMap.Add(fullName, imageInfo); } } break; } case "PerfInfo/PMCSample": { PMCCounterProfTraceData traceData = (PMCCounterProfTraceData)data; if (traceData.ProcessID == benchmarkPid) { ulong instructionPointer = traceData.InstructionPointer; // Not sure how to find the PMC reload interval... sigh ulong count = 1; UpdateSampleCountMap(instructionPointer, count); UpdateThreadCountMap(traceData.ThreadID, count); } break; } } }; source.Clr.All += delegate(TraceEvent data) { if (allEventCounts.ContainsKey(data.EventName)) { allEventCounts[data.EventName]++; } else { allEventCounts[data.EventName] = 1; } if (data.ProcessID == benchmarkPid) { if (eventCounts.ContainsKey(data.EventName)) { eventCounts[data.EventName]++; } else { eventCounts[data.EventName] = 1; } switch (data.EventName) { case "Method/JittingStarted": { MethodJittingStartedTraceData jitStartData = (MethodJittingStartedTraceData)data; JitInvocation jitInvocation = new JitInvocation(); jitInvocation.ThreadId = jitStartData.ThreadID; jitInvocation.MethodId = jitStartData.MethodID; jitInvocation.InitialThreadCount = ThreadCountMap[jitInvocation.ThreadId]; ActiveJitInvocations.Add(jitInvocation.ThreadId, jitInvocation); AllJitInvocations.Add(jitInvocation); break; } case "Method/LoadVerbose": { MethodLoadUnloadVerboseTraceData loadUnloadData = (MethodLoadUnloadVerboseTraceData)data; if (ActiveJitInvocations.ContainsKey(loadUnloadData.ThreadID)) { JitInvocation j = ActiveJitInvocations[loadUnloadData.ThreadID]; ActiveJitInvocations.Remove(j.ThreadId); j.FinalThreadCount = ThreadCountMap[j.ThreadId]; if (j.FinalThreadCount < j.InitialThreadCount) { Console.WriteLine("eh? negative jit count..."); } else { JitSampleCount += j.FinalThreadCount - j.InitialThreadCount; } } else { // ? } break; } case "Method/UnloadVerbose": { // Pretend this is an "image" MethodLoadUnloadVerboseTraceData loadUnloadData = (MethodLoadUnloadVerboseTraceData)data; string fullName = GetName(loadUnloadData); string key = fullName + "@" + loadUnloadData.MethodID.ToString("X"); if (!ImageMap.ContainsKey(key)) { ImageInfo methodInfo = new ImageInfo(fullName, loadUnloadData.MethodStartAddress, loadUnloadData.MethodSize); ImageMap.Add(key, methodInfo); methodInfo.IsJitGeneratedCode = true; methodInfo.IsJittedCode = loadUnloadData.IsJitted; } //else //{ // Console.WriteLine("eh? see method {0} again in rundown", fullName); //} break; } } } }; source.Process(); } AttributeSampleCounts(); //foreach (var e in allEventCounts) //{ // Console.WriteLine("Event {0} occurred {1} times", e.Key, e.Value); //} //foreach (var e in processCounts) //{ // Console.WriteLine("Process {0} had {1} events", e.Key, e.Value); //} if (!eventCounts.ContainsKey("PerfInfo/PMCSample")) { Console.WriteLine("No PMC events seen, sorry."); } else { ulong InstrsPerEvent = 65536; ulong pmcEvents = eventCounts["PerfInfo/PMCSample"]; Console.WriteLine("InstRetired for {0}: {1} events, {2:E} instrs", benchmarkName, pmcEvents, pmcEvents * InstrsPerEvent); Console.WriteLine("Jitting : {0:00.00%} ({1} methods)", (double)JitSampleCount / TotalSampleCount, AllJitInvocations.Count); // Console.WriteLine(" JitInterface : {0:00.00%}", (double) JitSampleCount - JitDllSampleCount); Console.WriteLine("Jit-generated code: {0:00.00%}", (double)JitGeneratedCodeSampleCount / TotalSampleCount); Console.WriteLine(" Jitted code : {0:00.00%}", (double)JittedCodeSampleCount / TotalSampleCount); Console.WriteLine(); double ufrac = (double)UnknownImageCount / TotalSampleCount; if (ufrac > 0.002) { Console.WriteLine("{0:00.00%} {1,-8:G3} {2} {3}", ufrac, UnknownImageCount * InstrsPerEvent, "? ", "Unknown"); } // Collect up significant counts List <ImageInfo> significantInfos = new List <ImageInfo>(); foreach (var i in ImageMap) { double frac = (double)i.Value.SampleCount / TotalSampleCount; if (frac > 0.002) { significantInfos.Add(i.Value); } } significantInfos.Sort(ImageInfo.MoreSamples); foreach (var i in significantInfos) { Console.WriteLine("{0:00.00%} {1,-8:G3} {2} {3}", (double)i.SampleCount / TotalSampleCount, i.SampleCount * InstrsPerEvent, i.IsJitGeneratedCode ? (i.IsJittedCode ? "jit " : "prejit") : "native", i.Name); } } }
private void Kernel_ProcessStart(ProcessTraceData obj) { myProcessStartEvents.Add((ProcessTraceData)obj.Clone()); }