static void Main(string[] args) { var stop = new ManualResetEvent(false); var engine = new MDbgEngine(); var process = engine.CreateProcess(@"c:\users\marcin\documents\visual studio 2010\Projects\ConsoleApplication9\ConsoleApplication9\bin\Release\ConsoleApplication9.exe", "", DebugModeFlag.Default, null); process.Go(); process.PostDebugEvent += (sender, e) => { if (e.CallbackType == ManagedCallbackType.OnBreakpoint) { process.Go(); } if (e.CallbackType == ManagedCallbackType.OnException2) { var e2 = (CorException2EventArgs)e.CallbackArgs; //Console.WriteLine(ClrDump.CreateDump(process.CorProcess.Id, @"E:\temp.dmp", (int)MINIDUMP_TYPE.MiniDumpWithFullMemory, 0, IntPtr.Zero)); } if (e.CallbackType == ManagedCallbackType.OnProcessExit) { stop.Set(); } }; stop.WaitOne(); }
private static void Main(string[] args) { MDbgProcess proc = null; try { int processId = Int32.Parse(args[0]); MDbgEngine debugger = new MDbgEngine(); proc = debugger.Attach(processId); InitializeMdbg(debugger, proc); DumpThreads(proc); } catch { PrintUsage(); } finally { if (proc != null) { // We always want to detach from target. proc.Detach().WaitOne(); } } }
public static MDbgEngine invoke_Method(this MDbgEngine engine, string moduleName, string typeName, string methodName, CorValue[] parameters) { var module = engine.module(moduleName); var function = engine.activeProcess().ResolveFunctionName(module, typeName, methodName); return(engine.invoke_Method(function.CorFunction, parameters)); }
public static MDbgEngine invoke_Method(this MethodInfo methodInfo, MDbgEngine engine, CorValue[] parameters) { // var methodInfo = debugger.module("mscorlib").type("System.Console").method("Write"); var module = engine.process().ResolveClass(methodInfo.DeclaringType.FullName).Module; var corFunction = module.GetFunctionFromToken(methodInfo.MetadataToken); return(engine.invoke_Method(corFunction, parameters)); }
public static MDbgEngine detach(this MDbgEngine engine) { if (engine.hasActiveProcess()) { engine.process().Detach().WaitOne(); } return(engine); }
public static MDbgProcess activeProcess(this MDbgEngine engine) { if (engine.Processes.size() > 0) { return(engine.Processes.Active); } return(null); }
public static MDbgEngine attach(this MDbgEngine engine, Process process) { if (process.isNull()) { "[MDbgEngine] in attach provided process object was null".error(); return(engine); } return(engine.attach(process.Id)); }
public static MDbgEngine process_StopInNSeconds(this MDbgEngine engine, int seconds) { O2Thread.mtaThread( () => { engine.sleep(seconds * 1000); engine.stop_Process(); }); return(engine); }
public static CorGenericValue create_Object(this MDbgEngine engine, CorElementType elementType, object value) { var corEval = engine.corEval(); var corClass = engine.process().ResolveClass(value.typeFullName()); var corValue = corEval.CreateValue(elementType, corClass); var genericValue = corValue.CastToGenericValue(); return(genericValue.value(value)); }
public static CorValue create_String(this MDbgEngine engine, string stringValue) { CorEval eval = engine.corEval(); eval.NewString(stringValue); engine.goAndWait(); CorValue corValue = (engine.activeProcess().StopReason as EvalCompleteStopReason).Eval.Result; return(corValue); }
public static CorValue[] corValues(this MDbgEngine engine, params string[] stringValues) { var corValues = new List <CorValue>(); foreach (var stringValue in stringValues) { corValues.add(engine.create_String(stringValue)); } return(corValues.ToArray()); }
public static List <MDbgModule> modules(this MDbgEngine engine) { var modules = new List <MDbgModule>(); foreach (MDbgModule module in engine.activeProcess().Modules) { modules.Add(module); } return(modules); }
public static List <MDbgThread> threads(this MDbgEngine engine) { var threads = new List <MDbgThread>(); foreach (MDbgThread thread in engine.activeProcess().Threads) { threads.add(thread); } return(threads); }
public static MDbgEngine stop_Process(this MDbgEngine engine) { if (engine.activeProcess().notNull()) { "[MDbgEngine] in stop_Process".info(); engine.@break(); engine.activeProcess().Kill(); } return(engine); }
public static string GetCurrentLocationInSource(MDbgEngine debugger, IShell shell) { if (!debugger.Processes.Active.Threads.HaveActive) { return(""); // we won't try to show current location } MDbgThread thr = debugger.Processes.Active.Threads.Active; MDbgSourcePosition pos = thr.CurrentSourcePosition; if (pos == null) { MDbgFrame f = thr.CurrentFrame; if (f.IsManaged) { CorDebugMappingResult mappingResult; uint ip; f.CorFrame.GetIP(out ip, out mappingResult); string s = "IP: " + ip + " @ " + f.Function.FullName + " - " + mappingResult; return(s); } else { return("<Located in native code.>"); } } else { string fileLoc = shell.FileLocator.GetFileLocation(pos.Path); if (fileLoc == null) { // Using the full path makes debugging output inconsistant during automated test runs. // For testing purposes we'll get rid of them. //CommandBase.WriteOutput("located at line "+pos.Line + " in "+ pos.Path); return("located at line " + pos.Line + " in " + System.IO.Path.GetFileName(pos.Path)); } else { IMDbgSourceFile file = shell.SourceFileMgr.GetSourceFile(fileLoc); string prefixStr = pos.Line.ToString(CultureInfo.InvariantCulture) + ":"; if (pos.Line < 1 || pos.Line > file.Count) { shell.WriteLine("located at line " + pos.Line + " in " + pos.Path); throw new Exception(string.Format("Could not display current location; file {0} doesn't have line {1}.", file.Path, pos.Line)); } Debug.Assert((pos.Line > 0) && (pos.Line <= file.Count)); return(file[pos.Line]); } } }
private static void InitializeMdbg(MDbgEngine debugger, MDbgProcess proc) { bool stopOnNewThread = debugger.Options.StopOnNewThread; debugger.Options.StopOnNewThread = false; proc.Go().WaitOne(); debugger.Options.StopOnNewThread = true; while (proc.CorProcess.HasQueuedCallbacks(null)) { proc.Go().WaitOne(); } debugger.Options.StopOnNewThread = stopOnNewThread; }
private static void RunDebugger(string args) { Console.WriteLine("Starting debugger for: {0}", args); var stop = new ManualResetEvent(false); var engine = new MDbgEngine(); engine.Options.CreateProcessWithNewConsole = true; var process = engine.CreateProcess( null, string.Format("\"{0}\" {1}", Assembly.GetExecutingAssembly().Location, args), DebugModeFlag.Default, null); process.PostDebugEvent += (sender, e) => { if (e.CallbackType == ManagedCallbackType.OnBreakpoint) { SetBreakPoint(process); Console.WriteLine(); Console.WriteLine("--- Can I haz breakpoint? ---"); var ce = (CorBreakpointEventArgs)e.CallbackArgs; DumpLocals(process.Threads.Lookup(ce.Thread).CurrentFrame); process.Go(); } if (e.CallbackType == ManagedCallbackType.OnException2) { Console.WriteLine(); Console.WriteLine("--- Oh noes, exception! ---"); var ce = (CorException2EventArgs)e.CallbackArgs; if (ce.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE) { //DumpThread(process.Threads.Lookup(ce.Thread)); MiniDump(Path.Combine(Directory.GetCurrentDirectory(), "minidump.dmp"), process.CorProcess.Id); } } if (e.CallbackType == ManagedCallbackType.OnProcessExit) { stop.Set(); } }; process.Go(); stop.WaitOne(); }
public static MDbgEngine invoke_Method(this MDbgEngine engine, CorFunction function, CorValue[] parameters) { try { var eval = engine.corEval(); eval.CallFunction(function, parameters); engine.goAndWait(); } catch (Exception ex) { "[MDbgEngine] invoke_Method: {0}".error(ex.Message); } return(engine); }
private void InitDebugging() { this.configuration = ReadConfiguration(options.Config); SymbolCache = new MDbgSymbolCache(); Debugger = new MDbgEngine(); BreakpointParser = new DefaultBreakpointParser(this); FileLocator = new MDbgFileLocator(); SourceFileMgr = new MDbgSourceFileMgr(); PdbSymbolCache = new PdbSymbolCache(configuration.assemblies.Select(a => a.path), this); languageUtils = new List <ILanguageUtil>(new[] { new CSharpLanguageUtil() }); methodLocators = new Dictionary <string, MethodLocator>(); foreach (var assembly in configuration.assemblies) { methodLocators[assembly.path] = new MethodLocator(assembly.path, assembly.language, this); } }
private void DrainAttach(MDbgEngine debugger, MDbgProcess proc) { bool fOldStatus = debugger.Options.StopOnNewThread; debugger.Options.StopOnNewThread = false; // skip while waiting for AttachComplete proc.Go().WaitOne(); Debug.Assert(proc.StopReason is AttachCompleteStopReason); debugger.Options.StopOnNewThread = true; // needed for attach= true; // needed for attach // Drain the rest of the thread create events. while (proc.CorProcess.HasQueuedCallbacks(null)) { proc.Go().WaitOne(); Debug.Assert(proc.StopReason is ThreadCreatedStopReason); } debugger.Options.StopOnNewThread = fOldStatus; }
/// <summary> /// 利用VS调试工具输出线程堆栈测试 http://blogs.msdn.com/b/jmstall/archive/2005/11/28/snapshot.aspx /// </summary> /// <param name="args"></param> static void Main(string[] args) { do { Console.WriteLine("pid?"); int pid; if (!int.TryParse(Console.ReadLine(), out pid)) { return; } MDbgEngine debugger = new MDbgEngine(); MDbgProcess proc = null; try { proc = debugger.Attach(pid); DrainAttach(debugger, proc); MDbgThreadCollection tc = proc.Threads; Console.WriteLine("Attached to pid:{0}", pid); foreach (MDbgThread t in tc) { Console.WriteLine("Callstack for Thread {0}", t.Id.ToString()); foreach (MDbgFrame f in t.Frames) { Console.WriteLine(" " + f); } } } finally { if (proc != null) { proc.Detach().WaitOne(); } } }while (true); }
public static List <Process> attachableProcesses(this MDbgEngine engine) { var attachableProcesses = new List <Process>(); foreach (var process in Process.GetProcesses()) { if (Process.GetCurrentProcess().Id == process.Id) // let's hide our process { continue; } CLRMetaHost mh = null; try { mh = new CLRMetaHost(); } catch (System.EntryPointNotFoundException) { continue; } IEnumerable <CLRRuntimeInfo> runtimes = null; try { runtimes = mh.EnumerateLoadedRuntimes(process.Id); } catch { continue; } //if there are no runtimes in the target process, don't print it out if (!runtimes.GetEnumerator().MoveNext()) { continue; } attachableProcesses.add(process); } return(attachableProcesses); }
// Expects 1 arg, the pid as a decimal string private static void Main(string[] args) { try { int pid = int.Parse(args[0]); var sb = new StringBuilder(); Process process = Process.GetProcessById(pid); //var counters = new Dictionary<string, MyThreadCounterInfo>(); //var threadInfos = new Dictionary<string, MyThreadInfo>(); ////zhanggangb //sb.AppendFormat( // @"<html><head><title>{0}</title><style type=""text/css"">table, td{{border: 1px solid #000;border-collapse: collapse;}}</style></head><body>", // process.ProcessName); //Console.WriteLine("1、正在收集计数器:"); //var cate = new PerformanceCounterCategory("Thread"); //string[] instances = cate.GetInstanceNames(); //foreach (string instance in instances) //{ // if (instance.StartsWith(process.ProcessName, StringComparison.CurrentCultureIgnoreCase)) // { // var counter1 = // new PerformanceCounter("Thread", "ID Thread", instance, true); // var counter2 = // new PerformanceCounter("Thread", "% Processor Time", instance, true); // counters.Add(instance, new MyThreadCounterInfo(counter1, counter2)); // } //} //foreach (var pair in counters) //{ // try // { // pair.Value.IdCounter.NextValue(); // pair.Value.ProcessorTimeCounter.NextValue(); // } // catch(Exception ex) // { // Console.WriteLine(ex.Message); // } //} //Thread.Sleep(5000); //foreach (var pair in counters) //{ // try // { // var info = new MyThreadInfo(); // info.Id = pair.Value.IdCounter.NextValue().ToString(); // info.ProcessorTimePercentage = pair.Value.ProcessorTimeCounter.NextValue().ToString("0.0"); // threadInfos.Add(info.Id, info); // } // catch(Exception ex) // { // Console.WriteLine(ex.Message); // } //} //Console.WriteLine("2、正在收集线程信息"); //ProcessThreadCollection collection = process.Threads; //foreach (ProcessThread thread in collection) //{ // try // { // MyThreadInfo info; // if (threadInfos.TryGetValue(thread.Id.ToString(), out info)) // { // info.UserProcessorTime = thread.UserProcessorTime.ToString(); // info.StartTime = thread.StartTime.ToString(); // } // } // catch (Exception ex) // { // Console.WriteLine(ex.Message); // } //} var debugger = new MDbgEngine(); debugger.Options.StopOnException = true; StringBuilder sbb = new StringBuilder(); MDbgProcess proc = null; try { proc = debugger.Attach(pid); DrainAttach(debugger, proc); var tc = proc.Threads; Console.WriteLine("3、正在附加到进程{0}获取调用栈", pid); foreach (MDbgThread t in tc) { var tempStrs = new StringBuilder(); foreach (MDbgFrame f in t.Frames) { tempStrs.AppendFormat("<br />" + f); } MyThreadInfo info; if (threadInfos.TryGetValue(t.Id.ToString(), out info)) { info.CallStack = tempStrs.Length == 0 ? "no managment call stack" : tempStrs.ToString(); sb.Append(info.CallStack); } } } finally { if (proc != null) { proc.Detach().WaitOne(); } } Console.WriteLine("4、正在生成报表"); using (var sw = new StreamWriter(@"D:\View\MYBLOG\CpuAnalyzer\bin\Debug\" + process.Id + ".htm", false, Encoding.Default)) { sw.Write(sbb.ToString()); } //按照cpu占用率排序 //var result = threadInfos.Values.ToArray().OrderByDescending(item => double.Parse(item.ProcessorTimePercentage)); //foreach (var info in result) //{ // sb.Append(info.ToString()); // sb.Append("<hr />"); //} //sb.Append("</body></html>"); //Console.WriteLine("4、正在生成报表"); //using (var sw = new StreamWriter(@"D:\View\MYBLOG\CpuAnalyzer\bin\Debug\"+process.Id + ".htm", false, // Encoding.Default)) //{ // sw.Write(sb.ToString()); //} Process.Start(@"D:\View\MYBLOG\CpuAnalyzer\bin\Debug\" + process.Id + ".htm"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("分析结束"); Console.ReadKey(); }
public static MDbgEngine goAndWait(this MDbgEngine engine) { engine.activeProcess().goAndWait(); return(engine); }
public static MDbgProcess process(this MDbgEngine engine) { return(engine.activeProcess()); }
public static bool hasActiveProcess(this MDbgEngine engine) { return(engine.activeProcess().notNull()); }
public static MDbgEngine startProcess(this MDbgEngine engine, string exeToDebug, string arguments = "") { engine.CreateProcess(exeToDebug, arguments, DebugModeFlag.Debug, null); return(engine); }
public static MDbgEngine console_WriteLine(this MDbgEngine engine, string message) { typeof(Console).method_bySignature("Void WriteLine(System.String)") .invoke_Method(engine, message); return(engine); }
public static MDbgEngine console_WriteLine(this MDbgEngine engine) { return(engine.invoke_Method("mscorlib", "System.Console", "WriteLine")); }
public static MDbgEngine invoke_Method(this MethodInfo methodInfo, MDbgEngine engine, params string[] stringValues) { var corValues = engine.corValues(stringValues); return(methodInfo.invoke_Method(engine, corValues)); }