Ejemplo n.º 1
0
        public void Attach(MDbgProcess process)
        {
            process.PostDebugEvent +=
                (sender, e) =>
            {
                log.Log(e.CallbackType.ToString());

                if (e.CallbackType == ManagedCallbackType.OnException2)
                {
                    var ce = (CorException2EventArgs)e.CallbackArgs;

                    if (ce.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE)
                    {
                        var thread = process.Threads.Lookup(ce.Thread);

                        foreach (var frame in thread.Frames)
                        {
                            if (!frame.IsManaged || frame.Function.FullName.StartsWith("System."))
                            {
                                break;
                            }

                            log.Log("{0}({1})", frame.Function.FullName, string.Join(", ", frame.Function.GetArguments(frame).Select(
                                                                                         arg => string.Format("{0} = {1}", arg.Name, arg.GetStringValue(false)))));
                        }
                    }
                }
            };
        }
Ejemplo n.º 2
0
        public void AnalyseExecutionPosition()
        {
            if (!shell.Debugger.Processes.HaveActive)
            {
                ReportDebugTermination();
                return; // don't try to display current location
            }
            else
            {
                if (lastActiveprocess == null)
                {
                    shell.Debugger.Processes.Active.PostDebugEvent += OnPostDebugEvent;
                    lastActiveprocessId = shell.Debugger.Processes.Active.CorProcess.Id;
                    MessageQueue.AddNotification(NppCategory.Process + lastActiveprocessId + ":STARTED");
                    lastActiveprocess = shell.Debugger.Processes.Active;
                }

                try
                {
                    ReportCurrentState();
                    ReportWatch();
                }
                catch
                {
                }
            }
        }
Ejemplo n.º 3
0
        // O2.Debugger.Mdbg.OriginalMdbgCode.mdbg.mdbgCommandsCustomizedForO2
        // , O2Thread.FuncVoid<string> o2Callback)
        public static bool AttachCmd(string arguments, O2Thread.FuncVoidT1 <string> o2Callback)
        {
            try
            {
                var ap = new ArgParser(arguments);
                if (ap.Count > 1)
                {
                    DI.log.error("in AttachCmd: Wrong # of arguments.");
                    return(false);
                }

                if (!ap.Exists(0))
                {
                    DI.log.error("in AttachCmd: Please choose some process to attach");
                    MdbgCommands.ProcessEnumCmd("");
                    return(false);
                }
                int pid = ap.AsInt(0);

                if (Process.GetCurrentProcess().Id == pid)
                {
                    DI.log.error("in AttachCmd: Cannot attach to myself!");
                    return(false);
                }

                MDbgProcess p = CommandBase.Debugger.Attach(pid);
                p.Go().WaitOne();
                return(true);
            }
            catch (Exception ex)
            {
                DI.log.ex(ex, "in AttachCmd");
                return(false);
            }
        }
Ejemplo n.º 4
0
        // Return class as a string.
        /// <summary>
        /// Creates a string representation of CorType.
        /// </summary>
        /// <param name="proc">A debugged process.</param>
        /// <param name="ct">A CorType object representing a type in the debugged process.</param>
        /// <returns>String representaion of the passed in type.</returns>
        public static string PrintCorType(MDbgProcess proc, CorType ct)
        {
            var sb = new StringBuilder();

            PrintCorType(sb, proc, ct);
            return(sb.ToString());
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Creates a new instance of the MDbgValue Object.
 /// This constructor is public so that applications can use this class to print values (CorValue).
 /// CorValue's can be returned for example by funceval(CorEval.Result).
 /// </summary>
 /// <param name="process">The Process that will own the Value.</param>
 /// <param name="value">The CorValue that this MDbgValue will start with.</param>
 public MDbgValue(MDbgProcess process, CorDebug.CorValue value)
 {
     // value can be null, but we should always know what process we are
     // looking at.
     Debug.Assert(process != null);
     Initialize(process, null, value);
 }
Ejemplo n.º 6
0
        public void StartProcess()
        {
            Debugger.Options.StopOnLogMessage = false;
            if (options.PID != 0)
            {
                string clrVersion = string.IsNullOrEmpty(options.CLRVersion) ? MdbgVersionPolicy.GetDefaultAttachVersion(options.PID) : options.CLRVersion;
                Process = Debugger.Attach(options.PID, null, clrVersion);
                WriteLine("Attached to " + options.PID);
                Process.Go().WaitOne();
            }
            else if (!string.IsNullOrEmpty(options.Executable))
            {
                var clrVersion = MdbgVersionPolicy.GetDefaultLaunchVersion(options.Executable);
                Process = Debugger.Processes.CreateLocalProcess(new CorDebugger(clrVersion));
                if (Process == null)
                {
                    throw new Exception("Could not create debugging interface for runtime version " + clrVersion);
                }
                Process.DebugMode = DebugModeFlag.Debug;
                Process.CreateProcess(options.Executable, configuration.arguments != null ? configuration.arguments : "");
                Process.Go().WaitOne();
            }
            else
            {
                WriteLine(options.GetUsage());
                return;
            }

            Console.CancelKeyPress += OnAbort;
        }
Ejemplo n.º 7
0
        } // refresh

        void EvalWatch(MDbgProcess proc)
        {
            Console.WriteLine("-------------------");
            try
            {
                //public class Test { public int MyProp { get; set; } }
                //...
                //var t = new Test();
                //t.MyProp = 9;
                string expression = "t.MyProp";
                expression = "printer";
                //expression = "d";

                MDbgValue value = proc.ResolveVariable(expression, proc.Threads.Active.CurrentFrame);

                if (value != null)
                {
                    //Console.WriteLine(expression + ": " + value.InvokeToString());
                    //Console.WriteLine(expression + ": " + value.InvokeMethod("Test").InvokeToString());
                    Console.WriteLine(expression + ": " + value.InvokeMethod("Ping"));
                    //Console.WriteLine(expression + ": " + value.InvokeMethod("Who").InvokeToString());
                    //Console.WriteLine(expression + ": " + value.InvokeMethod("Who1").InvokeToString());
                    //Console.WriteLine(expression + ": " + value.GetStringValue(false));
                }
                Console.WriteLine("#################");
            }
            catch
            {
                //expressionValue = "<items/>";
                Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            }
            Console.WriteLine("-------------------");
        }
Ejemplo n.º 8
0
        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();
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a default 'source level step' on process with current active frame and active thread.
        /// </summary>
        /// <param name="process">non-null process </param>
        /// <param name="type">type of step (in, out, over)</param>
        /// <param name="singleStepInstructions">false to step source level, true to step single instructions</param>
        /// <returns></returns>
        public static StepperDescriptor CreateSourceLevelStep(MDbgProcess process, StepperType type, bool singleStepInstructions)
        {
            StepperDescriptor s = new StepperDescriptor(process);

            s.StepperType = type;

            //
            // Handle Step-out case.
            //
            if (type == StepperType.Out)
            {
                return(s);
            }

            //
            // Handle step-over / step-in case
            //
            bool stepInto = (type == StepperType.In);

            // Cache current
            s.Thread = process.Threads.Active.CorThread;
            s.Frame  = s.Thread.ActiveFrame;

            CorDebugMappingResult mappingResult;
            uint ip;

            if (!singleStepInstructions)
            {
                // For source-level stepping, skip some interceptors. These are random, and cause
                // random differences in stepping across different runtimes; and user generally don't care
                // about interceptors.
                // It's actually a debatable policy about which interceptors to skip and stop on.
                s.InterceptMask = CorDebugIntercept.INTERCEPT_ALL &
                                  ~(CorDebugIntercept.INTERCEPT_SECURITY | CorDebugIntercept.INTERCEPT_CLASS_INIT);
            }

            s.Frame.GetIP(out ip, out mappingResult);
            if (singleStepInstructions ||
                (mappingResult != CorDebugMappingResult.MAPPING_EXACT &&
                 mappingResult != CorDebugMappingResult.MAPPING_APPROXIMATE))
            {
                // Leave step ranges null
            }
            else
            {
                // Getting the step ranges is what really makes this a source-level step.
                MDbgFunction           f  = process.Modules.LookupFunction(s.Frame.Function);
                COR_DEBUG_STEP_RANGE[] sr = f.GetStepRangesFromIP((int)ip);
                if (sr != null)
                {
                    s.SetStepRanges(sr, true);
                }
                else
                {
                    // Leave step ranges null.
                }
            }

            return(s);
        }
Ejemplo n.º 10
0
        public void Attach(MDbgProcess process)
        {
            //foreach (MDbgModule module in process.Modules)
            //    module.

            //process.SymbolPath =
        }
Ejemplo n.º 11
0
 private static void DumpThreads(MDbgProcess proc)
 {
     foreach (MDbgThread thread in (IEnumerable)proc.Threads)
     {
         DumpThread(thread);
     }
 }
Ejemplo n.º 12
0
        private void WriteMdbgPrompt(bool processStopped)
        {
            string s;

            if (processStopped)
            {
                MDbgProcess p = null;
                if (m_shell.Debugger.Processes.HaveActive)
                {
                    p = m_shell.Debugger.Processes.Active;
                    if (p.Threads.HaveActive)
                    {
                        s = "[p#:" + p.Number + ", t#:" + p.Threads.Active.Number + "] ";
                    }
                    else
                    {
                        s = "[p#:" + p.Number + ", t#:no active thread] ";
                    }
                }
                else
                {
                    s = "";
                }
            }
            else
            {
                s = "[process running] ";
            }
            Console.Write(s + TEXT_PROMPT_STRING);
        }
Ejemplo n.º 13
0
        string GetCurrentSourcePosition()
        {
            if (!shell.Debugger.Processes.HaveActive)
            {
                return(null);
            }

            MDbgProcess process = shell.Debugger.Processes.Active;

            if (process.IsRunning)
            {
                return(null);
            }

            if (!process.Threads.Active.HaveCurrentFrame)
            {
                return(null); //No frame for current thread #" + thread.Number);
            }
            if (!process.Threads.Active.CurrentFrame.IsInfoOnly)
            {
                return(FormatSourcePosition(process.Threads.Active.CurrentFrame));
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 14
0
 internal MDbgModule(MDbgProcess process, CorModule managedModule, int number)
 {
     Debug.Assert(process != null && managedModule != null);
     m_process   = process;
     m_module    = managedModule;
     m_functions = new MDbgFunctionMgr(this);
     m_number    = number;
 }
Ejemplo n.º 15
0
 internal MDbgAppDomain(MDbgProcess process, CorDebug.CorAppDomain appDomain, int number)
 {
     Debug.Assert(process != null);
     Debug.Assert(appDomain != null);
     m_process   = process;
     m_appDomain = appDomain;
     m_number    = number;
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Creates an empty stepper.
 /// </summary>
 /// <param name="process">non-null process that this is stepping</param>
 public StepperDescriptor(MDbgProcess process)
 {
     if (process == null)
     {
         throw new ArgumentNullException("process");
     }
     m_process = process;
 }
Ejemplo n.º 17
0
        public static CorValue CreateCorValue(this MDbgProcess process, string value)
        {
            CorEval eval = process.Threads.Active.CorThread.CreateEval();

            eval.NewString(value);
            process.Go().WaitOne();
            return((process.StopReason as EvalCompleteStopReason).Eval.Result);
        }
Ejemplo n.º 18
0
        private void Cleanup()
        {
            MDbgProcess active = Debugger.Processes.Active;

            active.Breakpoints.DeleteAll();

            active.CorProcess.Stop(0);
            active.Detach();
        }
Ejemplo n.º 19
0
        //////////////////////////////////////////////////////////////////////////////////
        //
        // Controlling Commands
        //
        //////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// creates a new debugged process.
        /// </summary>
        /// <param name="commandLine">The command to run.</param>
        /// <param name="commandArguments">The arguments for the command.</param>
        /// <param name="debugMode">The debug mode to run with.</param>
        /// <param name="deeVersion">The version of debugging interfaces that should be used for
        ///   debuging of the started program. If this value is null, the default (latest) version
        ///   of interface is used.
        /// </param>
        /// <returns>The resulting MDbgProcess.</returns>
        public MDbgProcess CreateProcess(string commandLine, string commandArguments,
                                         DebugModeFlag debugMode, string deeVersion)
        {
            MDbgProcess p = m_processMgr.CreateLocalProcess(deeVersion);

            p.DebugMode = debugMode;
            p.CreateProcess(commandLine, commandArguments);
            return(p);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Attach to a process with the given Process ID
        /// Only debug the specified CLR version; all others are ignored.
        /// </summary>
        /// <param name="processId">The Process ID to attach to.</param>
        /// <param name="attachContinuationEvent">A OS event handle which must be set to unblock the debuggee
        /// when first continuing from attach</param>
        /// <param name="version">The version string for the CLR instance to debug.</param>
        /// <returns>The resulting MDbgProcess.</returns>
        public MDbgProcess Attach(int processId,
                                  Microsoft.Samples.Debugging.Native.SafeWin32Handle attachContinuationEvent,
                                  string version)
        {
            Debug.Assert(version != null);
            MDbgProcess p = m_processMgr.CreateLocalProcess(new CorDebugger(version));

            p.Attach(processId, attachContinuationEvent);
            return(p);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Acts on debugger callback based on the contained stop option policies matching
 /// the callback type.
 /// </summary>
 /// <param name="currentProcess">Current MDbgProcess.</param>
 /// <param name="args">Debugger callback arguments.</param>
 public void ActOnCallback(MDbgProcess currentProcess, CustomPostCallbackEventArgs args)
 {
     if (m_stopOptions[(int)args.CallbackType] != null)
     {
         foreach (MDbgStopOptionPolicy sop in m_stopOptions[(int)args.CallbackType])
         {
             sop.ActOnCallback(currentProcess, args);
         }
     }
 }
Ejemplo n.º 22
0
        void ReportDebugTermination()
        {
            if (lastActiveprocess != null)
            {
                MessageQueue.AddNotification(NppCategory.Process + lastActiveprocessId + ":STOPPED");
                MessageQueue.AddCommand(NppCommand.Exit); //to close all communication channels

                lastActiveprocess   = null;
                lastActiveprocessId = 0;
            }
        }
        /// <summary>
        /// Acts on the debugger callback, based on the stop option policy settings and the
        /// type of exception thrown.
        /// </summary>
        /// <param name="currentProcess">Current MDbgProcess.</param>
        /// <param name="args">Callback arguments.</param>
        public override void ActOnCallback(MDbgProcess currentProcess, CustomPostCallbackEventArgs args)
        {
            var  ea          = args.CallbackArgs as CorException2EventArgs;
            var  ua          = args.CallbackArgs as CorExceptionUnwind2EventArgs;
            bool bException2 = (ea != null);

            if (m_exceptionEnhancedOn ||
                (bException2 && (ea.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE)))
            {
                MDbgThread currentThread = null;
                currentThread =
                    currentProcess.Threads.GetThreadFromThreadId((args.CallbackArgs as CorThreadEventArgs).Thread.Id);

                string exceptionType = currentThread.CurrentException.TypeName;

                switch (DetermineBehavior(exceptionType))
                {
                case DebuggerBehavior.Stop:
                    if (bException2)
                    {
                        args.Controller.Stop(ea.Thread, new ExceptionThrownStopReason(ea.AppDomain,
                                                                                      ea.Thread, ea.Frame, ea.Offset,
                                                                                      ea.EventType, ea.Flags,
                                                                                      m_exceptionEnhancedOn));
                    }
                    else
                    {
                        args.Controller.Stop(ua.Thread, new ExceptionUnwindStopReason(ua.AppDomain,
                                                                                      ua.Thread, ua.EventType,
                                                                                      ua.Flags));
                    }
                    break;

                case DebuggerBehavior.Log:
                    CommandBase.WriteOutput("Exception thrown: " + currentThread.CurrentException.TypeName +
                                            " at function " + currentThread.CurrentFrame.Function.FullName +
                                            " in source file " + currentThread.CurrentSourcePosition.Path +
                                            ":" + currentThread.CurrentSourcePosition.Line);
                    if (m_exceptionEnhancedOn)
                    {
                        if (bException2)
                        {
                            CommandBase.WriteOutput("Event type: " + ea.EventType);
                        }
                        else
                        {
                            CommandBase.WriteOutput("Event type: " + ua.EventType);
                        }
                    }
                    CommandBase.WriteOutput("");
                    break;
                }
            }
        }
Ejemplo n.º 24
0
        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;
        }
Ejemplo n.º 25
0
        public Mdbg()
        {
            process = engine.Processes.CreateLocalProcess();

            string cmd = ServiceHost.Discovery.NetRuntimeSDK;

            if (cmd == null)
            {
                return;
            }

            reader      = new Thread(new ThreadStart(ReaderLoop));
            reader.Name = "Cordbg reader";
            reader.Start();
        }
Ejemplo n.º 26
0
        // Helper to append generic args from tyenum in pretty format.
        // This will add a string like '<int, Foo<string>>'
        internal static void AddGenericArgs(StringBuilder sb, MDbgProcess proc, IEnumerable tyenum)
        {
            int i = 0;

            foreach (CorType t1 in tyenum)
            {
                sb.Append((i == 0) ? '<' : ',');
                PrintCorType(sb, proc, t1);
                i++;
            }
            if (i > 0)
            {
                sb.Append('>');
            }
        }
Ejemplo n.º 27
0
 private static void SetBreakPoint(MDbgProcess process)
 {
     if (process.Breakpoints.Count == 0)
     {
         try
         {
             var module     = process.Modules.Lookup(Assembly.GetExecutingAssembly().Location);
             var document   = module.SymReader.GetDocuments().Single(d => Path.GetFileName(d.URL) == "Program.Debugee.cs");
             var breakpoint = process.Breakpoints.CreateBreakpoint(document.URL, 77);
         }
         catch (Exception exception)
         {
             Console.WriteLine(exception);
         }
     }
 }
        /// <summary>
        /// Acts on the current callback, based on the current debugger behavior for this stop
        /// option policy.
        /// </summary>
        /// <param name="currentProcess">Current MDbgProcess.</param>
        /// <param name="args">Callback arguments.</param>
        public override void ActOnCallback(MDbgProcess currentProcess, CustomPostCallbackEventArgs args)
        {
            var eventArgs = args.CallbackArgs as CorEventArgs;

            switch (m_behavior)
            {
            case DebuggerBehavior.Stop:
                args.Controller.Stop(eventArgs.Thread,
                                     MDbgUtil.CreateStopReasonFromEventArgs(eventArgs, currentProcess));
                break;

            case DebuggerBehavior.Log:
                CommandBase.WriteOutput(eventArgs + "\n");
                break;
            }
        }
Ejemplo n.º 29
0
        // Helper to append generic args from tyenum in pretty format.
        // This will add a string like '<int, Foo<string>>'
        internal static void AddGenericArgs(StringBuilder sb, MDbgProcess proc, IEnumerable tyenum)
        {
            int i = 0;

            foreach (CorType t1 in tyenum)
            {
                sb.Append((i == 0) ? '<' : ',');
                InternalUtil.PrintCorType(sb, proc, t1);
                i++;
            }
            if (i > 0)
            {
                sb.Append('>');
                //System.Collections.Generic.List`1 //zos; CSScript.Npp related changes
                sb.Replace("`" + i, "");
            }
        }
Ejemplo n.º 30
0
        //////////////////////////////////////////////////////////////////////////////////
        //
        // Controlling Commands
        //
        //////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// creates a new debugged process.
        /// </summary>
        /// <param name="commandLine">The command to run.</param>
        /// <param name="commandArguments">The arguments for the command.</param>
        /// <param name="debugMode">The debug mode to run with.</param>
        /// <param name="deeVersion">The version of debugging interfaces that should be used for
        ///   debugging of the started program. If this value is null, the default (latest) version
        ///   of interface is used.
        /// </param>
        /// <returns>The resulting MDbgProcess.</returns>
        public MDbgProcess CreateProcess(string commandLine, string commandArguments,
                                         DebugModeFlag debugMode, string deeVersion)
        {
            CorDebugger debugger;

            if (deeVersion == null)
            {
                debugger = new CorDebugger(CorDebugger.GetDefaultDebuggerVersion());
            }
            else
            {
                debugger = new CorDebugger(deeVersion);
            }
            MDbgProcess p = m_processMgr.CreateLocalProcess(debugger);

            p.DebugMode = debugMode;
            p.CreateProcess(commandLine, commandArguments);
            return(p);
        }