public CorMethodCall(CorEvaluationContext context, CorFunction function, CorType[] typeArgs, CorValue[] args) { this.context = context; this.function = function; this.typeArgs = typeArgs; this.args = args; eval = context.Eval; }
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); }
void CheckTimestamp( ) { if (evalTimestamp != CorDebuggerSession.EvaluationTimestamp) { thread = null; frame = null; corEval = null; } }
public CorValue CreateString(string value) { CorEval eval = process.Threads.Active.CorThread.CreateEval(); eval.NewString(value); return(GetResult()); //return ParseValue("\"" + 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 void Serialize(string path, IEnumerable <MDbgValue> valuesList) { var values = valuesList.ToList(); CorEval eval = debugger.Processes.Active.Threads.Active.CorThread.CreateEval(); var functionName = "BigBrother.Serialization.JsonSerializer.Serialize" + (values.Count + 1); CorAppDomain appDomain = debugger.Processes.Active.Threads.Active.CorThread.AppDomain; if (serializers.Count == 0) { //Load BigBrother into the AppDomain. Then we can call BigBrother.Serialization.JsonSerializer's methods. if (useLoadFrom) { eval.NewString("BigBrother.dll"); debugger.Processes.Active.Go().WaitOne(); var evalAssemblyName = eval.Result; var fnLoad = debugger.Processes.Active.ResolveFunctionNameFromScope("System.Reflection.Assembly.LoadFrom", appDomain); eval.CallParameterizedFunction(fnLoad.CorFunction, null, new CorValue[] { evalAssemblyName }); debugger.Processes.Active.Go().WaitOne(); } else { eval.NewString("BigBrother"); debugger.Processes.Active.Go().WaitOne(); var evalAssemblyName = eval.Result; var fnLoad = debugger.Processes.Active.ResolveFunctionNameFromScope("System.Reflection.Assembly.Load", appDomain); eval.CallParameterizedFunction(fnLoad.CorFunction, null, new CorValue[] { evalAssemblyName }); debugger.Processes.Active.Go().WaitOne(); } } if (!serializers.ContainsKey(functionName)) { serializers[functionName] = debugger.Processes.Active.ResolveFunctionNameFromScope(functionName, appDomain); } eval.NewString(path); debugger.Processes.Active.Go().WaitOne(); CorValue fileName = (debugger.Processes.Active.StopReason as EvalCompleteStopReason).Eval.Result; var corValues = new List <CorValue>(); corValues.Add(fileName); corValues.AddRange(values.Select(v => v.CorValue)); eval.CallParameterizedFunction(serializers[functionName].CorFunction, corValues.Select(v => v.ExactType).ToArray(), corValues.ToArray()); debugger.Processes.Active.Go().WaitOne(); if (debugger.Processes.Active.StopReason is EvalExceptionStopReason) { var stopReason = (EvalExceptionStopReason)debugger.Processes.Active.StopReason; string message = new MDbgValue(debugger.Processes.Active, stopReason.Eval.Result).GetStringValue(true); shell.WriteLine(message); } }
public CorValue Invoke(string methodName, CorValue instance, params CorValue[] args) { var allArgs = new List <CorValue>(); if (instance != null) { allArgs.Add(instance); } allArgs.AddRange(args); MDbgFunction func = process.ResolveFunctionNameFromScope(methodName); if (null == func) { throw new Exception(String.Format(CultureInfo.InvariantCulture, "Could not resolve {0}", new Object[] { methodName })); } CorEval eval = process.Threads.Active.CorThread.CreateEval(); // Get Variables ArrayList vars = new ArrayList(); String arg; foreach (var v in allArgs) { if (v is CorGenericValue) { vars.Add(v as CorValue); } else { CorHeapValue hv = v.CastToHeapValue(); if (hv != null) { // we cannot pass directly heap values, we need to pass reference to heap valus CorReferenceValue myref = eval.CreateValue(CorElementType.ELEMENT_TYPE_CLASS, null).CastToReferenceValue(); myref.Value = hv.Address; vars.Add(myref); } else { vars.Add(v); } } } eval.CallFunction(func.CorFunction, (CorValue[])vars.ToArray(typeof(CorValue))); return(GetResult()); }
CorValue GetResult() { process.Go().WaitOne(); // now display result of the funceval if (process.StopReason is EvalCompleteStopReason) { eval = (process.StopReason as EvalCompleteStopReason).Eval; Debug.Assert(eval != null); return(eval.Result); } return(null); }
/// <summary> /// Eval a function in the target process. /// </summary> /// <param name="functionNameFromScope">The full function name.</param> MDbgValue FunctionEval(string functionNameFromScope) { CorAppDomain corAD = this.MDbgProcess.Threads.Active.CorThread.AppDomain; MDbgFunction function = this.MDbgProcess.ResolveFunctionNameFromScope( functionNameFromScope, corAD); CorEval eval = this.MDbgProcess.Threads.Active.CorThread.CreateEval(); eval.CallFunction(function.CorFunction, new CorValue[0]); MDbgProcess.Go().WaitOne(); MDbgValue value = null; if (MDbgProcess.StopReason is EvalCompleteStopReason) { CorValue result = (MDbgProcess.StopReason as EvalCompleteStopReason).Eval.Result; if (result != null) { value = new MDbgValue(MDbgProcess, result); } } return(value); }
public static void FuncEvalCmd(string arguments, IMDbgShell Shell, O2Thread.FuncVoidT1 <string> execOnEval) { try { var activeProcess = DI.o2MDbg.ActiveProcess; //Debugger.Processes.Active const string appDomainOption = "ad"; var ap = new ArgParser(arguments, appDomainOption + ":1"); if (!(ap.Count >= 1)) { throw new MDbgShellException("Not Enough arguments"); } // Currently debugger picks first function -- we have not implementing resolving overloaded functions. // Good example is Console.WriteLine -- there is 18 different types: // 1) [06000575] Void WriteLine() // 2) [06000576] Void WriteLine(Boolean) // 3) [06000577] Void WriteLine(Char) // 4) [06000578] Void WriteLine(Char[]) // 5) [06000579] Void WriteLine(Char[], Int32, Int32) // 6) [0600057a] Void WriteLine(Decimal) // 7) [0600057b] Void WriteLine(Double) // 8) [0600057c] Void WriteLine(Single) // 9) [0600057d] Void WriteLine(Int32) // 10) [0600057e] Void WriteLine(UInt32) // 11) [0600057f] Void WriteLine(Int64) // 12) [06000580] Void WriteLine(UInt64) // 13) [06000581] Void WriteLine(Object) // 14) [06000582] Void WriteLine(String) // 15) [06000583] Void WriteLine(String, Object) // 16) [06000584] Void WriteLine(String, Object, Object) // 17) [06000585] Void WriteLine(String, Object, Object, Object) // 18) [06000586] Void WriteLine(String, Object, Object, Object, Object, ...) // 19) [06000587] Void WriteLine(String, Object[]) // CorAppDomain appDomain; if (ap.OptionPassed(appDomainOption)) { MDbgAppDomain ad = activeProcess.AppDomains[ap.GetOption(appDomainOption).AsInt]; if (ad == null) { throw new ArgumentException("Invalid Appdomain Number"); } appDomain = ad.CorAppDomain; } else { appDomain = activeProcess.Threads.Active.CorThread.AppDomain; } MDbgFunction func = activeProcess.ResolveFunctionNameFromScope(ap.AsString(0), appDomain); if (null == func) { throw new MDbgShellException(String.Format(CultureInfo.InvariantCulture, "Could not resolve {0}", new Object[] { ap.AsString(0) })); } CorEval eval = activeProcess.Threads.Active.CorThread.CreateEval(); // Get Variables var vars = new ArrayList(); String arg; for (int i = 1; i < ap.Count; i++) { arg = ap.AsString(i); CorValue v = Shell.ExpressionParser.ParseExpression2(arg, activeProcess, activeProcess.Threads.Active. CurrentFrame); if (v == null) { throw new MDbgShellException("Cannot resolve expression or variable " + ap.AsString(i)); } if (v is CorGenericValue) { vars.Add(v); } else { CorHeapValue hv = v.CastToHeapValue(); if (hv != null) { // we cannot pass directly heap values, we need to pass reference to heap valus CorReferenceValue myref = eval.CreateValue(CorElementType.ELEMENT_TYPE_CLASS, null).CastToReferenceValue(); myref.Value = hv.Address; vars.Add(myref); } else { vars.Add(v); } } } eval.CallFunction(func.CorFunction, (CorValue[])vars.ToArray(typeof(CorValue))); activeProcess.Go().WaitOne(); // now display result of the funceval if (!(activeProcess.StopReason is EvalCompleteStopReason)) { // we could have received also EvalExceptionStopReason but it's derived from EvalCompleteStopReason Shell.IO.WriteOutput(MDbgOutputConstants.StdOutput, "Func-eval not fully completed and debuggee has stopped"); Shell.IO.WriteOutput(MDbgOutputConstants.StdOutput, "Result of funceval won't be printed when finished."); } else { eval = (activeProcess.StopReason as EvalCompleteStopReason).Eval; Debug.Assert(eval != null); CorValue cv = eval.Result; if (cv != null) { var mv = new MDbgValue(activeProcess, cv); if (execOnEval != null) // if this callback is set then execute { execOnEval(mv.GetStringValue(1)); return; } Shell.IO.WriteOutput(MDbgOutputConstants.StdOutput, "result = " + mv.GetStringValue(1)); if (cv.CastToReferenceValue() != null) { if (activeProcess.DebuggerVars.SetEvalResult(cv)) { Shell.IO.WriteOutput(MDbgOutputConstants.StdOutput, "results saved to $result"); } } } } } catch (Exception ex) { DI.log.ex(ex, "in FuncEvalCmd"); } if (execOnEval != null) // need to call this here so that the sync AutoResetEvent is set { execOnEval(null); } }
public void SetThread(CorThread thread) { if (thread == null) throw new InvalidOperationException(); ICorDebugEval ce; int hr = thread.RawObject.CreateEval(out ce); if (hr < 0 || ce == null) throw new EvalException(hr, string.Format("Could not create an evaluator, HR=0x{0:X8}", hr)); this.thread = thread; this.eval = new CorEval(ce); }
public CorValue RuntimeInvoke(CorEvaluationContext ctx, CorFunction function, CorType[] typeArgs, CorValue thisObj, CorValue[] arguments) { if (!ctx.Thread.ActiveChain.IsManaged) { throw new EvaluatorException("Cannot evaluate expression because the thread is stopped in native code."); } CorValue[] args; if (thisObj == null) { args = arguments; } else { args = new CorValue[arguments.Length + 1]; args[0] = thisObj; arguments.CopyTo(args, 1); } CorMethodCall mc = new CorMethodCall(); CorValue exception = null; CorEval eval = ctx.Eval; EvalEventHandler completeHandler = delegate(object o, CorEvalEventArgs eargs) { OnEndEvaluating(); mc.DoneEvent.Set(); eargs.Continue = false; }; EvalEventHandler exceptionHandler = delegate(object o, CorEvalEventArgs eargs) { OnEndEvaluating(); exception = eargs.Eval.Result; mc.DoneEvent.Set(); eargs.Continue = false; }; process.OnEvalComplete += completeHandler; process.OnEvalException += exceptionHandler; mc.OnInvoke = delegate { if (function.GetMethodInfo(this).Name == ".ctor") { eval.NewParameterizedObject(function, typeArgs, args); } else { eval.CallParameterizedFunction(function, typeArgs, args); } process.SetAllThreadsDebugState(CorDebugThreadState.THREAD_SUSPEND, ctx.Thread); ClearEvalStatus(); OnStartEvaluating(); process.Continue(false); }; mc.OnAbort = delegate { eval.Abort(); }; mc.OnGetDescription = delegate { System.Reflection.MethodInfo met = function.GetMethodInfo(ctx.Session); if (met != null) { return(met.Name); } else { return("<Unknown>"); } }; try { ObjectAdapter.AsyncExecute(mc, ctx.Options.EvaluationTimeout); } finally { process.OnEvalComplete -= completeHandler; process.OnEvalException -= exceptionHandler; } if (exception != null) { /* ValueReference<CorValue, CorType> msg = ctx.Adapter.GetMember (ctx, val, "Message"); * if (msg != null) { * string s = msg.ObjectValue as string; * mc.ExceptionMessage = s; * } * else * mc.ExceptionMessage = "Evaluation failed.";*/ CorValRef vref = new CorValRef(exception); throw new EvaluatorException("Evaluation failed: " + ObjectAdapter.GetValueTypeName(ctx, vref)); } return(eval.Result); }
private string PrintObject(int indentLevel, CorObjectValue ov, int expandDepth, bool canDoFunceval) { Debug.Assert(expandDepth >= 0); bool fNeedToResumeThreads = true; // Print generics-aware type. string name = InternalUtil.PrintCorType(this.m_process, ov.ExactType); StringBuilder txt = new StringBuilder(); txt.Append(name); if (expandDepth > 0) { // we gather the field info of the class before we do // funceval since funceval requires running the debugger process // and this in turn can cause GC and invalidate our references. StringBuilder expandedDescription = new StringBuilder(); if (IsComplexType) { foreach (MDbgValue v in GetFields()) { expandedDescription.Append("\n").Append(IndentedString(indentLevel + 1, v.Name)). Append("=").Append(IndentedBlock(indentLevel + 2, v.GetStringValue(expandDepth - 1, false))); } } // if the value we're printing is a nullable type that has no value (is null), we can't do a func eval // to get its value, since it will be boxed as a null pointer. We already have the information we need, so // we'll just take care of it now. Note that ToString() for null-valued nullable types just prints the // empty string. // bool hasValue = (bool)(GetField("hasValue").CorValue.CastToGenericValue().GetValue()); if (IsNullableType(ov.ExactType) && !(bool)(GetField("hasValue").CorValue.CastToGenericValue().GetValue())) { txt.Append(" < >"); } else if (ov.IsValueClass && canDoFunceval) // we could display even values for real Objects, but we will just show // "description" for valueclasses. { CorClass cls = ov.ExactType.Class; CorMetadataImport importer = m_process.Modules.Lookup(cls.Module).Importer; MetadataType mdType = importer.GetType(cls.Token) as MetadataType; if (mdType.ReallyIsEnum) { txt.AppendFormat(" <{0}>", InternalGetEnumString(ov, mdType)); } else if (m_process.IsRunning) { txt.Append(" <N/A during run>"); } else { MDbgThread activeThread = m_process.Threads.Active; CorValue thisValue; CorHeapValue hv = ov.CastToHeapValue(); if (hv != null) { // we need to pass reference value. CorHandleValue handle = hv.CreateHandle(CorDebugHandleType.HANDLE_WEAK_TRACK_RESURRECTION); thisValue = handle; } else { thisValue = ov; } try { CorEval eval = m_process.Threads.Active.CorThread.CreateEval(); m_process.CorProcess.SetAllThreadsDebugState(CorDebugThreadState.THREAD_SUSPEND, activeThread.CorThread); MDbgFunction toStringFunc = m_process.ResolveFunctionName(null, "System.Object", "ToString", thisValue.ExactType.Class.Module.Assembly.AppDomain)[0]; Debug.Assert(toStringFunc != null); // we should be always able to resolve ToString function. eval.CallFunction(toStringFunc.CorFunction, new CorValue[] { thisValue }); m_process.Go(); do { m_process.StopEvent.WaitOne(); if (m_process.StopReason is EvalCompleteStopReason) { CorValue cv = eval.Result; Debug.Assert(cv != null); MDbgValue mv = new MDbgValue(m_process, cv); string valName = mv.GetStringValue(0); // just purely for esthetical reasons we 'discard' " if (valName.StartsWith("\"") && valName.EndsWith("\"")) { valName = valName.Substring(1, valName.Length - 2); } txt.Append(" <").Append(valName).Append(">"); break; } if ((m_process.StopReason is ProcessExitedStopReason) || (m_process.StopReason is EvalExceptionStopReason)) { txt.Append(" <N/A cannot evaluate>"); break; } // hitting bp or whatever should not matter -- we need to ignore it m_process.Go(); }while (true); } catch (COMException e) { // Ignore cannot copy a VC class error - Can't copy a VC with object refs in it. if (e.ErrorCode != (int)HResult.CORDBG_E_OBJECT_IS_NOT_COPYABLE_VALUE_CLASS) { throw; } } catch (System.NotImplementedException) { fNeedToResumeThreads = false; } finally { if (fNeedToResumeThreads) { // we need to resume all the threads that we have suspended no matter what. m_process.CorProcess.SetAllThreadsDebugState(CorDebugThreadState.THREAD_RUN, activeThread.CorThread); } } } } txt.Append(expandedDescription.ToString()); } return(txt.ToString()); }
public ExpressionParsingResult ParseExpression(string expression) { //the expression is either setter of method invoke var result = new ExpressionParsingResult(); result.IsSetter = expression.IsSetExpression(); result.Expression = expression; int bracketIndex = expression.IndexOfAny(new[] { '(', '=' }); string methodName = expression.Substring(0, bracketIndex).Trim(); string args = expression.Substring(bracketIndex).Replace("(", "").Replace(")", "").Replace("=", "").Trim(); string[] methodParts = methodName.Split('.'); if (methodParts.Length == 1 && result.IsSetter) //myVar=3 { result.IsLocalVariable = true; } result.ExpressionValue = args; string reference; if (methodParts.Length == 1) { //varName reference = methodParts[0]; } else { //<<TypeName>|<CodeReference>>.<MethodName> reference = string.Join(".", methodParts.Take(methodParts.Length - 1).ToArray()); } try { if ((expression.IsInvokeExpression() || expression.IsSetExpression()) && methodParts.Length == 1) { MDbgValue callingObject = process.ResolveVariable("this", process.Threads.Active.CurrentFrame); var mName = methodParts[0]; //either instance or static (e.g. "do()") MDbgFunction func = process.ResolveFunctionNameFromScope(mName); if (func != null) //method call { result.IsLocalVariable = false; if (func.MethodInfo.IsStatic) //static method call { result.Instance = null; result.Member = process.Threads.Active.CurrentFrame.Function.MethodInfo.DeclaringType.FullName + "." + mName; } else { result.Instance = callingObject.CorValue; result.Member = mName; } } else //variable assignment { var variable = process.ResolveVariable(reference, process.Threads.Active.CurrentFrame); if (variable != null)//local variable assignment { result.IsLocalVariable = true; result.Instance = variable.CorValue; result.Member = reference; } else { if (callingObject == null) //static member assignment { result.IsLocalVariable = false; result.Instance = null; result.Member = process.Threads.Active.CurrentFrame.Function.MethodInfo.DeclaringType.FullName + "." + mName; } else //instance member assignment { result.IsLocalVariable = false; result.Instance = callingObject.CorValue; result.Member = methodParts.Last(); } } } } else { var instance = process.ResolveVariable(reference, process.Threads.Active.CurrentFrame); if (instance != null) { result.Instance = instance.CorValue; result.Member = methodParts.Last(); } } } catch { } if (result.Instance == null && result.Member == null) { result.Member = methodName; } CorEval eval = process.Threads.Active.CorThread.CreateEval(); // Get Variables ArrayList vars = new ArrayList(); String arg; if (args.Length != 0) { foreach (var item in args.Split(',')) { arg = item.Trim(); CorValue v = process.m_engine.ParseExpression(arg, process, process.Threads.Active.CurrentFrame); if (v == null) { throw new Exception("Cannot resolve expression or variable " + arg); } if (v is CorGenericValue) { vars.Add(v as CorValue); } else { CorHeapValue hv = v.CastToHeapValue(); if (hv != null) { // we cannot pass directly heap values, we need to pass reference to heap valus CorReferenceValue myref = eval.CreateValue(CorElementType.ELEMENT_TYPE_CLASS, null).CastToReferenceValue(); myref.Value = hv.Address; vars.Add(myref); } else { vars.Add(v); } } } } result.Arguments = (CorValue[])vars.ToArray(typeof(CorValue)); return(result); }
public EvalHelper(MDbgProcess process) { this.process = process; eval = process.Threads.Active.CorThread.CreateEval(); }
// extensions might want to use this command stop reason // to signal finish of custom func-eval /// <summary> /// Creates a new instance of the EvalCompleteStopReason object. /// </summary> /// <param name="eval">The Function Evaluation that has completed.</param> public EvalCompleteStopReason(CorEval eval) { Debug.Assert(eval != null); m_eval = eval; }
// extensions might want to use this command stop reason // to signal finish of custom func-eval /// <summary> /// Creates a new instance of the EvalExceptionStopReason object. /// </summary> /// <param name="eval">The Function Evaluation that caused the exception.</param> public EvalExceptionStopReason(CorEval eval) : base(eval) { }