Browse Source

Add debugger core.

Add new NRefactory.
Add editor margin & bookmarks.
pull/191/merge
Eusebiu Marcu 15 years ago
parent
commit
c3ef036fd6
  1. 63
      Debugger/Debugger.Core/AppDomain.cs
  2. 24
      Debugger/Debugger.Core/AppDomainCollection.cs
  3. 70
      Debugger/Debugger.Core/ArrayDimension.cs
  4. 109
      Debugger/Debugger.Core/ArrayDimensions.cs
  5. 184
      Debugger/Debugger.Core/Breakpoint.cs
  6. 88
      Debugger/Debugger.Core/BreakpointCollection.cs
  7. 109
      Debugger/Debugger.Core/CollectionWithEvents.cs
  8. 28
      Debugger/Debugger.Core/DebuggeeState.cs
  9. 212
      Debugger/Debugger.Core/Debugger.Core.csproj
  10. 21
      Debugger/Debugger.Core/Debugger.Core.csproj.user
  11. 58
      Debugger/Debugger.Core/Debugger.Core.shfb
  12. 45
      Debugger/Debugger.Core/DebuggerException.cs
  13. 15
      Debugger/Debugger.Core/DebuggerObject.cs
  14. 416
      Debugger/Debugger.Core/Eval.cs
  15. 23
      Debugger/Debugger.Core/EvalCollection.cs
  16. 121
      Debugger/Debugger.Core/Exception.cs
  17. 13
      Debugger/Debugger.Core/ExceptionType.cs
  18. 56
      Debugger/Debugger.Core/GetValueException.cs
  19. 85
      Debugger/Debugger.Core/Interop/Common.cs
  20. 1632
      Debugger/Debugger.Core/Interop/CorDebug.cs
  21. 242
      Debugger/Debugger.Core/Interop/CorDebugExtensionMethods.cs
  22. 3342
      Debugger/Debugger.Core/Interop/CorDebugExtensionMethods.generated.cs
  23. 138
      Debugger/Debugger.Core/Interop/CorPublish.cs
  24. 15
      Debugger/Debugger.Core/Interop/CorPublishExtensionMethods.cs
  25. 273
      Debugger/Debugger.Core/Interop/CorPublishExtensionMethods.generated.cs
  26. 523
      Debugger/Debugger.Core/Interop/CorSym.cs
  27. 194
      Debugger/Debugger.Core/Interop/CorSymExtensionMethods.cs
  28. 901
      Debugger/Debugger.Core/Interop/CorSymExtensionMethods.generated.cs
  29. 252
      Debugger/Debugger.Core/Interop/MTA2STA.cs
  30. 278
      Debugger/Debugger.Core/Interop/MetaData.cs
  31. 1122
      Debugger/Debugger.Core/Interop/MetaDataWrapper.cs
  32. 28
      Debugger/Debugger.Core/Interop/NativeMethods.cs
  33. 57
      Debugger/Debugger.Core/Interop/TrackedComObjects.cs
  34. 68
      Debugger/Debugger.Core/Interop/Util.cs
  35. 552
      Debugger/Debugger.Core/ManagedCallback.cs
  36. 420
      Debugger/Debugger.Core/ManagedCallbackProxy.cs
  37. 400
      Debugger/Debugger.Core/ManagedCallbackSwitch.cs
  38. 133
      Debugger/Debugger.Core/MetaData/DebugConstructorInfo.cs
  39. 131
      Debugger/Debugger.Core/MetaData/DebugFieldInfo.cs
  40. 61
      Debugger/Debugger.Core/MetaData/DebugLocalVariableInfo.cs
  41. 664
      Debugger/Debugger.Core/MetaData/DebugMethodInfo.cs
  42. 67
      Debugger/Debugger.Core/MetaData/DebugParameterInfo.cs
  43. 244
      Debugger/Debugger.Core/MetaData/DebugPropertyInfo.cs
  44. 1377
      Debugger/Debugger.Core/MetaData/DebugType.cs
  45. 21
      Debugger/Debugger.Core/MetaData/IDebugMemberInfo.cs
  46. 14
      Debugger/Debugger.Core/MetaData/IOverloadable.cs
  47. 408
      Debugger/Debugger.Core/Module.cs
  48. 50
      Debugger/Debugger.Core/ModuleCollection.cs
  49. 53
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Binary/ImageFormatException.cs
  50. 49
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs
  51. 73
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs
  52. 55
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/MetadataFormatException.cs
  53. 99
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs
  54. 58
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs
  55. 649
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs
  56. 43
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Array.cs
  57. 43
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/ArrayShape.cs
  58. 53
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/BaseSignatureVisitor.cs
  59. 41
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Class.cs
  60. 37
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Constraint.cs
  61. 80
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/CustomAttrib.cs
  62. 48
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/CustomMod.cs
  63. 50
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/FieldSig.cs
  64. 41
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/FnPtr.cs
  65. 41
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/GenericArg.cs
  66. 46
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/GenericInst.cs
  67. 40
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/GenericInstSignature.cs
  68. 35
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/ISignatureVisitable.cs
  69. 39
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/ISignatureVisitor.cs
  70. 38
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/InputOutputItem.cs
  71. 58
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/LocalVarSig.cs
  72. 42
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MVar.cs
  73. 93
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MarshalSig.cs
  74. 48
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MethodDefSig.cs
  75. 49
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MethodRefSig.cs
  76. 50
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MethodSig.cs
  77. 40
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MethodSpec.cs
  78. 33
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Param.cs
  79. 52
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/PropertySig.cs
  80. 43
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Ptr.cs
  81. 39
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/RetType.cs
  82. 42
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/SigType.cs
  83. 50
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Signature.cs
  84. 991
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/SignatureReader.cs
  85. 520
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/SignatureWriter.cs
  86. 42
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/SzArray.cs
  87. 36
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/TypeSpec.cs
  88. 41
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/ValueType.cs
  89. 42
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Var.cs
  90. 43
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs
  91. 55
      Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil/ReflectionException.cs
  92. 320
      Debugger/Debugger.Core/NDebugger.cs
  93. 334
      Debugger/Debugger.Core/NRefactory/Ast/ExpressionExtensionMethods.cs
  94. 1015
      Debugger/Debugger.Core/NRefactory/Visitors/ExpressionEvaluator.cs
  95. 19
      Debugger/Debugger.Core/Options.cs
  96. 29
      Debugger/Debugger.Core/PauseSession.cs
  97. 22
      Debugger/Debugger.Core/PausedReason.cs
  98. 694
      Debugger/Debugger.Core/Process.cs
  99. 34
      Debugger/Debugger.Core/ProcessCollection.cs
  100. 22
      Debugger/Debugger.Core/ProcessEventArgs.cs
  101. Some files were not shown because too many files have changed in this diff Show More

63
Debugger/Debugger.Core/AppDomain.cs

@ -0,0 +1,63 @@ @@ -0,0 +1,63 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using Debugger.Interop.CorDebug;
using Debugger.MetaData;
using System.Collections.Generic;
namespace Debugger
{
public class AppDomain: DebuggerObject
{
Process process;
ICorDebugAppDomain corAppDomain;
internal Dictionary<ICorDebugType, DebugType> DebugTypeCache = new Dictionary<ICorDebugType, DebugType>();
public Process Process {
get { return process; }
}
public uint ID {
get {
return corAppDomain.GetID();
}
}
Module mscorlib;
public Module Mscorlib {
get {
if (mscorlib != null) return mscorlib;
foreach(Module m in Process.Modules) {
if (m.Name == "mscorlib.dll" &&
m.AppDomain == this) {
mscorlib = m;
return mscorlib;
}
}
throw new DebuggerException("Mscorlib not loaded");
}
}
internal DebugType ObjectType {
get { return DebugType.CreateFromType(this.Mscorlib, typeof(object)); }
}
internal ICorDebugAppDomain CorAppDomain {
get { return corAppDomain; }
}
internal ICorDebugAppDomain2 CorAppDomain2 {
get { return (ICorDebugAppDomain2)corAppDomain; }
}
public AppDomain(Process process, ICorDebugAppDomain corAppDomain)
{
this.process = process;
this.corAppDomain = corAppDomain;
}
}
}

24
Debugger/Debugger.Core/AppDomainCollection.cs

@ -0,0 +1,24 @@ @@ -0,0 +1,24 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using Debugger.Interop.CorDebug;
namespace Debugger
{
public class AppDomainCollection: CollectionWithEvents<AppDomain>
{
public AppDomainCollection(NDebugger dbgr): base(dbgr) {}
public AppDomain this[ICorDebugAppDomain corAppDomain] {
get {
foreach(AppDomain a in this) {
if (a.CorAppDomain.Equals(corAppDomain)) {
return a;
}
}
throw new DebuggerException("AppDomain not found");
}
}
}
}

70
Debugger/Debugger.Core/ArrayDimension.cs

@ -0,0 +1,70 @@ @@ -0,0 +1,70 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
namespace Debugger
{
/// <summary>
/// Specifies the range of valid indicies for an array dimension
/// </summary>
public class ArrayDimension
{
int lowerBound;
int upperBound;
/// <summary> The smallest valid index in this dimension </summary>
public int LowerBound {
get { return lowerBound; }
}
/// <summary> The largest valid index in this dimension.
/// Returns LowerBound - 1 if the array is empty. </summary>
public int UpperBound {
get { return upperBound; }
}
/// <summary> The number of valid indicies of this dimension </summary>
public int Count {
get { return upperBound - lowerBound + 1; }
}
/// <summary> Determines whether the given index is a valid index for this dimension </summary>
public bool IsIndexValid(int index)
{
return (this.LowerBound <= index && index <= this.UpperBound);
}
public ArrayDimension(int lowerBound, int upperBound)
{
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
public override string ToString()
{
if (this.LowerBound == 0) {
return this.Count.ToString();
} else {
return this.LowerBound + ".." + this.UpperBound;
}
}
public override int GetHashCode()
{
int hashCode = 0;
unchecked {
hashCode += 1000000007 * lowerBound.GetHashCode();
hashCode += 1000000009 * upperBound.GetHashCode();
}
return hashCode;
}
public override bool Equals(object obj)
{
ArrayDimension other = obj as ArrayDimension;
if (other == null) return false;
return this.lowerBound == other.lowerBound && this.upperBound == other.upperBound;
}
}
}

109
Debugger/Debugger.Core/ArrayDimensions.cs

@ -0,0 +1,109 @@ @@ -0,0 +1,109 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections;
using System.Collections.Generic;
namespace Debugger
{
/// <summary>
/// Specifies the range of valid indicies for all array dimensions
/// </summary>
public class ArrayDimensions: IEnumerable<ArrayDimension>
{
List<ArrayDimension> dimensions = new List<ArrayDimension>();
public IEnumerator<ArrayDimension> GetEnumerator()
{
return dimensions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)dimensions).GetEnumerator();
}
/// <summary> Gets a given dimension </summary>
public ArrayDimension this[int index] {
get {
return dimensions[index];
}
}
/// <summary> Get the number of dimensions of the array </summary>
public int Count {
get {
return dimensions.Count;
}
}
/// <summary> Get the total number of elements within the bounds
/// of an array specified by these dimensions. </summary>
public int TotalElementCount {
get {
int totalCount = 1;
foreach(ArrayDimension dim in this) {
totalCount *= dim.Count;
}
return totalCount;
}
}
/// <summary> Enumerate all vaild indicies in the array </summary>
public IEnumerable<int[]> Indices {
get {
foreach(ArrayDimension dim in this) {
if (dim.Count == 0) yield break;
}
int rank = this.Count;
int[] indices = new int[rank];
for(int i = 0; i < rank; i++) {
indices[i] = this[i].LowerBound;
}
while(true) { // Go thought all combinations
for (int i = rank - 1; i >= 1; i--) {
if (indices[i] > this[i].UpperBound) {
indices[i] = this[i].LowerBound;
indices[i - 1]++;
}
}
if (indices[0] > this[0].UpperBound) yield break; // We are done
yield return (int[])indices.Clone();
indices[rank - 1]++;
}
}
}
/// <summary> Determines whether the given index is a valid index for the array </summary>
public bool IsIndexValid(int[] indices)
{
for (int i = 0; i < this.Count; i++) {
if (!this[i].IsIndexValid(indices[i])) return false;
}
return true;
}
public ArrayDimensions(List<ArrayDimension> dimensions)
{
this.dimensions = dimensions;
}
public override string ToString()
{
string result = "[";
bool isFirst = true;
foreach(ArrayDimension dim in this) {
if (!isFirst) result += ", ";
result += dim.ToString();
isFirst = false;
}
result += "]";
return result;
}
}
}

184
Debugger/Debugger.Core/Breakpoint.cs

@ -0,0 +1,184 @@ @@ -0,0 +1,184 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Debugger.Interop.CorDebug;
namespace Debugger
{
public class Breakpoint: DebuggerObject
{
NDebugger debugger;
string fileName;
byte[] checkSum;
int line;
int column;
bool enabled;
SourcecodeSegment originalLocation;
List<ICorDebugFunctionBreakpoint> corBreakpoints = new List<ICorDebugFunctionBreakpoint>();
public event EventHandler<BreakpointEventArgs> Hit;
public event EventHandler<BreakpointEventArgs> Set;
[Debugger.Tests.Ignore]
public NDebugger Debugger {
get { return debugger; }
}
public string FileName {
get { return fileName; }
}
public byte[] CheckSum {
get { return checkSum; }
}
public int Line {
get { return line; }
set { line = value; }
}
public int Column {
get { return column; }
}
public bool Enabled {
get { return enabled; }
set {
enabled = value;
foreach(ICorDebugFunctionBreakpoint corBreakpoint in corBreakpoints) {
corBreakpoint.Activate(enabled ? 1 : 0);
}
}
}
public SourcecodeSegment OriginalLocation {
get { return originalLocation; }
}
public bool IsSet {
get {
return corBreakpoints.Count > 0;
}
}
protected virtual void OnHit(BreakpointEventArgs e)
{
if (Hit != null) {
Hit(this, e);
}
}
internal void NotifyHit()
{
OnHit(new BreakpointEventArgs(this));
debugger.Breakpoints.OnHit(this);
}
protected virtual void OnSet(BreakpointEventArgs e)
{
if (Set != null) {
Set(this, e);
}
}
public Breakpoint(NDebugger debugger, ICorDebugFunctionBreakpoint corBreakpoint)
{
this.debugger = debugger;
this.corBreakpoints.Add(corBreakpoint);
}
public Breakpoint(NDebugger debugger, string fileName, byte[] checkSum, int line, int column, bool enabled)
{
this.debugger = debugger;
this.fileName = fileName;
this.checkSum = checkSum;
this.line = line;
this.column = column;
this.enabled = enabled;
}
internal bool IsOwnerOf(ICorDebugBreakpoint breakpoint)
{
foreach(ICorDebugFunctionBreakpoint corFunBreakpoint in corBreakpoints) {
if (((ICorDebugBreakpoint)corFunBreakpoint).Equals(breakpoint)) return true;
}
return false;
}
internal void Deactivate()
{
foreach(ICorDebugFunctionBreakpoint corBreakpoint in corBreakpoints) {
#if DEBUG
// Get repro
corBreakpoint.Activate(0);
#else
try {
corBreakpoint.Activate(0);
} catch(COMException e) {
// Sometimes happens, but we had not repro yet.
// 0x80131301: Process was terminated.
if ((uint)e.ErrorCode == 0x80131301)
continue;
throw;
}
#endif
}
corBreakpoints.Clear();
}
internal void MarkAsDeactivated()
{
corBreakpoints.Clear();
}
internal bool SetBreakpoint(Module module)
{
if (this.fileName == null)
return false;
SourcecodeSegment segment = SourcecodeSegment.Resolve(module, FileName, CheckSum, Line, Column);
if (segment == null) return false;
originalLocation = segment;
ICorDebugFunctionBreakpoint corBreakpoint = segment.CorFunction.GetILCode().CreateBreakpoint((uint)segment.ILStart);
corBreakpoint.Activate(enabled ? 1 : 0);
corBreakpoints.Add(corBreakpoint);
OnSet(new BreakpointEventArgs(this));
return true;
}
/// <summary> Remove this breakpoint </summary>
public void Remove()
{
debugger.Breakpoints.Remove(this);
}
}
[Serializable]
public class BreakpointEventArgs : DebuggerEventArgs
{
Breakpoint breakpoint;
public Breakpoint Breakpoint {
get {
return breakpoint;
}
}
public BreakpointEventArgs(Breakpoint breakpoint): base(breakpoint.Debugger)
{
this.breakpoint = breakpoint;
}
}
}

88
Debugger/Debugger.Core/BreakpointCollection.cs

@ -0,0 +1,88 @@ @@ -0,0 +1,88 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using Debugger.Interop.CorDebug;
namespace Debugger
{
public class BreakpointCollection: CollectionWithEvents<Breakpoint>
{
public event EventHandler<CollectionItemEventArgs<Breakpoint>> Hit;
protected internal void OnHit(Breakpoint item)
{
if (Hit != null) {
Hit(this, new CollectionItemEventArgs<Breakpoint>(item));
}
}
public BreakpointCollection(NDebugger debugger):base(debugger) { }
internal Breakpoint this[ICorDebugBreakpoint corBreakpoint] {
get {
foreach (Breakpoint breakpoint in this) {
if (breakpoint.IsOwnerOf(corBreakpoint)) {
return breakpoint;
}
}
return null;
}
}
public new void Add(Breakpoint breakpoint)
{
base.Add(breakpoint);
}
public Breakpoint Add(string filename, int line)
{
Breakpoint breakpoint = new Breakpoint(this.Debugger, filename, null, line, 0, true);
Add(breakpoint);
return breakpoint;
}
public Breakpoint Add(string fileName, byte[] checkSum, int line, int column, bool enabled)
{
Breakpoint breakpoint = new Breakpoint(this.Debugger, fileName, checkSum, line, column, enabled);
Add(breakpoint);
return breakpoint;
}
protected override void OnAdded(Breakpoint breakpoint)
{
foreach(Process process in this.Debugger.Processes) {
foreach(Module module in process.Modules) {
breakpoint.SetBreakpoint(module);
}
}
base.OnAdded(breakpoint);
}
public new void Remove(Breakpoint breakpoint)
{
base.Remove(breakpoint);
}
protected override void OnRemoved(Breakpoint breakpoint)
{
breakpoint.Deactivate();
base.OnRemoved(breakpoint);
}
internal void SetInModule(Module module)
{
// This is in case that the client modifies the collection as a response to set breakpoint
// NB: If client adds new breakpoint, it will be set directly as a result of his call, not here (because module is already loaded)
List<Breakpoint> collection = new List<Breakpoint>();
collection.AddRange(this);
foreach (Breakpoint b in collection) {
b.SetBreakpoint(module);
}
}
}
}

109
Debugger/Debugger.Core/CollectionWithEvents.cs

@ -0,0 +1,109 @@ @@ -0,0 +1,109 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections;
using System.Collections.Generic;
namespace Debugger
{
public class CollectionItemEventArgs<T> : EventArgs
{
T item;
public T Item {
get {
return item;
}
}
public CollectionItemEventArgs(T item)
{
this.item = item;
}
}
/// <summary>
/// A collection that fires events when items are added or removed.
/// </summary>
public class CollectionWithEvents<T> : IEnumerable<T>
{
NDebugger debugger;
List<T> list = new List<T>();
public event EventHandler<CollectionItemEventArgs<T>> Added;
public event EventHandler<CollectionItemEventArgs<T>> Removed;
protected virtual void OnAdded(T item)
{
if (Added != null) {
Added(this, new CollectionItemEventArgs<T>(item));
}
}
protected virtual void OnRemoved(T item)
{
if (Removed != null) {
Removed(this, new CollectionItemEventArgs<T>(item));
}
}
public CollectionWithEvents(NDebugger debugger)
{
this.debugger = debugger;
}
protected NDebugger Debugger {
get {
return debugger;
}
}
public int Count {
get {
return list.Count;
}
}
public T this[int index] {
get {
return list[index];
}
}
internal void Add(T item)
{
list.Add(item);
OnAdded(item);
}
internal void Remove(T item)
{
if (list.Remove(item)) {
OnRemoved(item);
} else {
throw new DebuggerException("Item is not in the collection");
}
}
internal void Clear()
{
List<T> oldList = list;
list = new List<T>();
foreach (T item in oldList) {
OnRemoved(item);
}
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
}
}

28
Debugger/Debugger.Core/DebuggeeState.cs

@ -0,0 +1,28 @@ @@ -0,0 +1,28 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
namespace Debugger
{
/// <summary>
/// Represents span of time in which the debugger state is assumed to
/// be unchanged.
/// </summary>
/// <remarks>
/// For example, although property evaluation can in theory change
/// any memory, it is assumed that they behave 'correctly' and thus
/// property evaluation does not change debugger state.
/// </remarks>
public class DebuggeeState: DebuggerObject
{
Process process;
public Process Process {
get { return process; }
}
public DebuggeeState(Process process)
{
this.process = process;
}
}
}

212
Debugger/Debugger.Core/Debugger.Core.csproj

@ -0,0 +1,212 @@ @@ -0,0 +1,212 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1D18D788-F7EE-4585-A23B-34DC8EC63CB8}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Debugger</RootNamespace>
<AssemblyName>Debugger.Core</AssemblyName>
<AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<NoStdLib>False</NoStdLib>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>114294784</BaseAddress>
<PlatformTarget>AnyCPU</PlatformTarget>
<FileAlignment>4096</FileAlignment>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<OutputPath>..\..\..\..\AddIns\Debugger\</OutputPath>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<PublishUrl>http://localhost/Debugger.Core/</PublishUrl>
<Install>true</Install>
<InstallFrom>Web</InstallFrom>
<UpdateEnabled>true</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>true</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<Optimize>False</Optimize>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>PdbOnly</DebugType>
<Optimize>true</Optimize>
<DefineConstants>TRACE</DefineConstants>
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="Interop\MTA2STA.cs" />
<Compile Include="ManagedCallback.cs" />
<Compile Include="ManagedCallbackProxy.cs" />
<Compile Include="ManagedCallbackSwitch.cs" />
<Compile Include="MetaData\DebugConstructorInfo.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="AppDomain.cs" />
<Compile Include="AppDomainCollection.cs" />
<Compile Include="ArrayDimension.cs" />
<Compile Include="ArrayDimensions.cs" />
<Compile Include="Breakpoint.cs" />
<Compile Include="BreakpointCollection.cs" />
<Compile Include="CollectionWithEvents.cs" />
<Compile Include="DebuggeeState.cs" />
<Compile Include="DebuggerException.cs" />
<Compile Include="DebuggerObject.cs" />
<Compile Include="Eval.cs" />
<Compile Include="EvalCollection.cs" />
<Compile Include="Exception.cs" />
<Compile Include="ExceptionType.cs" />
<Compile Include="GetValueException.cs" />
<Compile Include="Interop\Common.cs" />
<Compile Include="Interop\CorDebug.cs" />
<Compile Include="Interop\CorDebugExtensionMethods.cs" />
<Compile Include="Interop\CorDebugExtensionMethods.generated.cs" />
<Compile Include="Interop\CorPublish.cs" />
<Compile Include="Interop\CorPublishExtensionMethods.cs" />
<Compile Include="Interop\CorPublishExtensionMethods.generated.cs" />
<Compile Include="Interop\CorSym.cs" />
<Compile Include="Interop\CorSymExtensionMethods.cs" />
<Compile Include="Interop\CorSymExtensionMethods.generated.cs" />
<Compile Include="Interop\MetaData.cs" />
<Compile Include="Interop\MetaDataWrapper.cs" />
<Compile Include="Interop\NativeMethods.cs" />
<Compile Include="Interop\TrackedComObjects.cs" />
<Compile Include="Interop\Util.cs" />
<Compile Include="MetaData\DebugFieldInfo.cs" />
<Compile Include="MetaData\DebugLocalVariableInfo.cs" />
<Compile Include="MetaData\DebugMethodInfo.cs" />
<Compile Include="MetaData\DebugParameterInfo.cs" />
<Compile Include="MetaData\DebugPropertyInfo.cs" />
<Compile Include="MetaData\DebugType.cs" />
<Compile Include="MetaData\IDebugMemberInfo.cs" />
<Compile Include="MetaData\IOverloadable.cs" />
<Compile Include="Module.cs" />
<Compile Include="ModuleCollection.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Binary\ImageFormatException.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Metadata\CodedIndex.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Metadata\ElementType.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Metadata\MetadataFormatException.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Metadata\MetadataToken.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Metadata\TokenType.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Metadata\Utilities.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\Array.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\ArrayShape.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\BaseSignatureVisitor.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\Class.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\Constraint.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\CustomMod.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\FieldSig.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\FnPtr.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\GenericArg.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\GenericInst.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\GenericInstSignature.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\InputOutputItem.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\ISignatureVisitable.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\ISignatureVisitor.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\LocalVarSig.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\MethodDefSig.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\MethodRefSig.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\MethodSig.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\MethodSpec.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\MVar.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\Param.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\PropertySig.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\Ptr.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\RetType.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\Signature.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\SignatureReader.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\SigType.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\SzArray.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\TypeSpec.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\ValueType.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil.Signatures\Var.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil\MethodCallingConvention.cs" />
<Compile Include="Mono.Cecil\Mono.Cecil\ReflectionException.cs" />
<Compile Include="NDebugger.cs" />
<Compile Include="NRefactory\Ast\ExpressionExtensionMethods.cs" />
<Compile Include="NRefactory\Visitors\ExpressionEvaluator.cs" />
<Compile Include="Options.cs" />
<Compile Include="PausedReason.cs" />
<Compile Include="PauseSession.cs" />
<Compile Include="Process.cs" />
<Compile Include="ProcessCollection.cs" />
<Compile Include="ProcessEventArgs.cs" />
<Compile Include="SourcecodeSegment.cs" />
<Compile Include="StackFrame.cs" />
<Compile Include="Stepper.cs" />
<Compile Include="Tests\ExpandAttribute.cs" />
<Compile Include="Tests\IgnoreAttribute.cs" />
<Compile Include="Tests\IgnoreOnExceptionAttribute.cs" />
<Compile Include="Thread.cs" />
<Compile Include="ThreadCollection.cs" />
<Compile Include="Value.cs" />
<None Include="Stepping.txt" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.2.0">
<Visible>False</Visible>
<ProductName>.NET Framework 2.0 %28x86%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
<Visible>False</Visible>
<ProductName>.NET Framework 3.0 %28x86%29</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Folder Include="Interop" />
<Folder Include="MetaData" />
<Folder Include="Mono.Cecil" />
<Folder Include="Mono.Cecil\Mono.Cecil" />
<Folder Include="Mono.Cecil\Mono.Cecil.Binary" />
<Folder Include="Mono.Cecil\Mono.Cecil.Metadata" />
<Folder Include="Mono.Cecil\Mono.Cecil.Signatures" />
<Folder Include="NRefactory" />
<Folder Include="NRefactory\Ast" />
<Folder Include="NRefactory\Visitors" />
<Folder Include="Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Decompiler\lib\NRefactory\Project\NRefactory.csproj">
<Project>{3A9AE6AA-BC07-4A2F-972C-581E3AE2F195}</Project>
<Name>NRefactory</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSHARP.Targets" />
</Project>

21
Debugger/Debugger.Core/Debugger.Core.csproj.user

@ -0,0 +1,21 @@ @@ -0,0 +1,21 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<LastOpenVersion>8.0.50215</LastOpenVersion>
<ProjectView>ProjectFiles</ProjectView>
<ProjectTrust>0</ProjectTrust>
<PublishUrlHistory>
</PublishUrlHistory>
<InstallUrlHistory>
</InstallUrlHistory>
<SupportUrlHistory>
</SupportUrlHistory>
<UpdateUrlHistory>
</UpdateUrlHistory>
<BootstrapperUrlHistory>
</BootstrapperUrlHistory>
<ErrorReportUrlHistory>
</ErrorReportUrlHistory>
<FallbackCulture>en-US</FallbackCulture>
<VerifyUploadedFiles>true</VerifyUploadedFiles>
</PropertyGroup>
</Project>

58
Debugger/Debugger.Core/Debugger.Core.shfb

@ -0,0 +1,58 @@ @@ -0,0 +1,58 @@
<project schemaVersion="1.6.0.2">
<assemblies>
<assembly assemblyPath="..\..\..\..\..\..\AddIns\AddIns\Misc\Debugger\Debugger.Core.dll" xmlCommentsPath="..\..\..\..\..\..\AddIns\AddIns\Misc\Debugger\Debugger.Core.xml" commentsOnly="False" />
</assemblies>
<namespaceSummaries>
<namespaceSummaryItem name="" isDocumented="False" />
<namespaceSummaryItem name="Debugger" isDocumented="True" />
<namespaceSummaryItem name="Debugger.Expressions" isDocumented="True" />
<namespaceSummaryItem name="Debugger.Interop" isDocumented="False" />
<namespaceSummaryItem name="Debugger.Interop.CorDebug" isDocumented="False" />
<namespaceSummaryItem name="Debugger.Interop.CorSym" isDocumented="False" />
<namespaceSummaryItem name="Debugger.Interop.MetaData" isDocumented="False" />
<namespaceSummaryItem name="Debugger.MetaData" isDocumented="True" />
<namespaceSummaryItem name="Debugger.Tests" isDocumented="False" />
<namespaceSummaryItem name="Debugger.Util" isDocumented="False" />
<namespaceSummaryItem name="Debugger.Wrappers" isDocumented="False" />
<namespaceSummaryItem name="Debugger.Wrappers.CorDebug" isDocumented="False" />
<namespaceSummaryItem name="Debugger.Wrappers.CorSym" isDocumented="False" />
<namespaceSummaryItem name="Debugger.Wrappers.MetaData" isDocumented="False" />
</namespaceSummaries>
<ProjectSummary>This library provides features for debugging managed applications.</ProjectSummary>
<MissingTags>Summary, Parameter, Returns, AutoDocumentCtors, Namespace</MissingTags>
<VisibleItems>InheritedMembers, Protected, SealedProtected</VisibleItems>
<HtmlHelp1xCompilerPath path="" />
<HtmlHelp2xCompilerPath path="" />
<OutputPath>.\docs\</OutputPath>
<SandcastlePath path="" />
<WorkingPath path="" />
<CleanIntermediates>True</CleanIntermediates>
<KeepLogFile>True</KeepLogFile>
<HelpFileFormat>HtmlHelp1x</HelpFileFormat>
<PurgeDuplicateTopics>True</PurgeDuplicateTopics>
<CppCommentsFixup>False</CppCommentsFixup>
<FrameworkVersion>2.0.50727</FrameworkVersion>
<BinaryTOC>True</BinaryTOC>
<IncludeFavorites>False</IncludeFavorites>
<Preliminary>False</Preliminary>
<RootNamespaceContainer>False</RootNamespaceContainer>
<RootNamespaceTitle />
<HelpTitle>Managed Debugger</HelpTitle>
<HtmlHelpName>Managed Debugger</HtmlHelpName>
<Language>en-US</Language>
<CopyrightHref />
<CopyrightText>2005-2008 David Srbecký</CopyrightText>
<FeedbackEMailAddress>dsrbecky@gmail.com</FeedbackEMailAddress>
<HeaderText />
<FooterText />
<ProjectLinkType>Local</ProjectLinkType>
<SdkLinkType>Msdn</SdkLinkType>
<SdkLinkTarget>Blank</SdkLinkTarget>
<PresentationStyle>Prototype</PresentationStyle>
<NamingMethod>Guid</NamingMethod>
<SyntaxFilters>Standard</SyntaxFilters>
<ShowFeedbackControl>False</ShowFeedbackControl>
<ContentPlacement>AboveNamespaces</ContentPlacement>
<ContentSiteMap path="" />
<TopicFileTransform path="" />
</project>

45
Debugger/Debugger.Core/DebuggerException.cs

@ -0,0 +1,45 @@ @@ -0,0 +1,45 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
namespace Debugger
{
/// <summary>
/// Type of exception thrown by the Debugger.
/// </summary>
public class DebuggerException: System.Exception
{
public DebuggerException() {}
public DebuggerException(string message): base(message) {}
public DebuggerException(string message, params object[] args): base(string.Format(message, args)) {}
public DebuggerException(string message, System.Exception inner): base(message, inner) {}
}
/// <summary>
/// An exception that is thrown when the debugged process unexpectedly exits.
/// </summary>
public class ProcessExitedException: DebuggerException
{
string processName = null;
/// <summary>
/// The name of the process that has exited.
/// </summary>
public string ProcessName {
get { return processName; }
}
/// <summary>
/// Creates a ProcessExitedException for an unnamed process.
/// </summary>
public ProcessExitedException(): base("Process exited") {}
/// <summary>
/// Creates a ProcessExitedException for a process.
/// </summary>
/// <param name="processName">The name of the process</param>
public ProcessExitedException(string processName): base(string.Format("Process '{0}' exited.", processName)) {
this.processName = processName;
}
}
}

15
Debugger/Debugger.Core/DebuggerObject.cs

@ -0,0 +1,15 @@ @@ -0,0 +1,15 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
namespace Debugger
{
/// <summary>
/// A base class for all classes declared by the debugger
/// </summary>
public class DebuggerObject: MarshalByRefObject
{
}
}

416
Debugger/Debugger.Core/Eval.cs

@ -0,0 +1,416 @@ @@ -0,0 +1,416 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Debugger.MetaData;
using Debugger.Interop.CorDebug;
namespace Debugger
{
public enum EvalState {
Evaluating,
EvaluatedSuccessfully,
EvaluatedException,
EvaluatedNoResult,
EvaluatedTimeOut,
};
/// <summary>
/// This class holds information about function evaluation.
/// </summary>
public class Eval: DebuggerObject
{
delegate void EvalStarter(Eval eval);
AppDomain appDomain;
Process process;
string description;
ICorDebugEval corEval;
Thread thread;
Value result;
EvalState state;
public AppDomain AppDomain {
get { return appDomain; }
}
public Process Process {
get { return process; }
}
public string Description {
get { return description; }
}
public ICorDebugEval CorEval {
get { return corEval; }
}
public ICorDebugEval2 CorEval2 {
get { return (ICorDebugEval2)corEval; }
}
/// <exception cref="GetValueException">Evaluating...</exception>
public Value Result {
get {
switch(this.State) {
case EvalState.Evaluating: throw new GetValueException("Evaluating...");
case EvalState.EvaluatedSuccessfully: return result;
case EvalState.EvaluatedException: return result;
case EvalState.EvaluatedNoResult: return null;
case EvalState.EvaluatedTimeOut: throw new GetValueException("Timeout");
default: throw new DebuggerException("Unknown state");
}
}
}
public EvalState State {
get { return state; }
}
public bool Evaluated {
get {
return state == EvalState.EvaluatedSuccessfully ||
state == EvalState.EvaluatedException ||
state == EvalState.EvaluatedNoResult ||
state == EvalState.EvaluatedTimeOut;
}
}
Eval(AppDomain appDomain, string description, EvalStarter evalStarter)
{
this.appDomain = appDomain;
this.process = appDomain.Process;
this.description = description;
this.state = EvalState.Evaluating;
this.thread = GetEvaluationThread(appDomain);
this.corEval = thread.CorThread.CreateEval();
try {
evalStarter(this);
} catch (COMException e) {
if ((uint)e.ErrorCode == 0x80131C26) {
throw new GetValueException("Can not evaluate in optimized code");
} else if ((uint)e.ErrorCode == 0x80131C28) {
throw new GetValueException("Object is in wrong AppDomain");
} else if ((uint)e.ErrorCode == 0x8013130A) {
// Happens on getting of Sytem.Threading.Thread.ManagedThreadId; See SD2-1116
throw new GetValueException("Function does not have IL code");
} else if ((uint)e.ErrorCode == 0x80131C23) {
// The operation failed because it is a GC unsafe point. (Exception from HRESULT: 0x80131C23)
// This can probably happen when we break and the thread is in native code
throw new GetValueException("Thread is in GC unsafe point");
} else if ((uint)e.ErrorCode == 0x80131C22) {
// The operation is illegal because of a stack overflow.
throw new GetValueException("Can not evaluate after stack overflow");
} else if ((uint)e.ErrorCode == 0x80131313) {
// Func eval cannot work. Bad starting point.
// Reproduction circumstancess are unknown
throw new GetValueException("Func eval cannot work. Bad starting point.");
} else {
#if DEBUG
throw; // Expose for more diagnostics
#else
throw new GetValueException(e.Message);
#endif
}
}
appDomain.Process.ActiveEvals.Add(this);
if (appDomain.Process.Options.SuspendOtherThreads) {
appDomain.Process.AsyncContinue(DebuggeeStateAction.Keep, new Thread[] { thread }, CorDebugThreadState.THREAD_SUSPEND);
} else {
appDomain.Process.AsyncContinue(DebuggeeStateAction.Keep, this.Process.UnsuspendedThreads, CorDebugThreadState.THREAD_RUN);
}
}
static Thread GetEvaluationThread(AppDomain appDomain)
{
appDomain.Process.AssertPaused();
Thread st = appDomain.Process.SelectedThread;
if (st != null && !st.Suspended && !st.IsInNativeCode && st.IsAtSafePoint && st.CorThread.GetAppDomain().GetID() == appDomain.ID) {
return st;
}
foreach(Thread t in appDomain.Process.Threads) {
if (!t.Suspended && !t.IsInNativeCode && t.IsAtSafePoint && t.CorThread.GetAppDomain().GetID() == appDomain.ID) {
return t;
}
}
throw new GetValueException("No suitable thread for evaluation");
}
internal bool IsCorEval(ICorDebugEval corEval)
{
return this.corEval == corEval;
}
/// <exception cref="DebuggerException">Evaluation can not be stopped</exception>
/// <exception cref="GetValueException">Process exited</exception>
Value WaitForResult()
{
// Note that aborting is not supported for suspended threads
try {
process.WaitForPause(TimeSpan.FromMilliseconds(500));
if (!Evaluated) {
process.TraceMessage("Aborting eval: " + Description);
this.CorEval.Abort();
process.WaitForPause(TimeSpan.FromMilliseconds(2500));
if (!Evaluated) {
process.TraceMessage("Rude aborting eval: " + Description);
this.CorEval2.RudeAbort();
process.WaitForPause(TimeSpan.FromMilliseconds(5000));
if (!Evaluated) {
throw new DebuggerException("Evaluation can not be stopped");
}
}
// Note that this sets Evaluated to true
state = EvalState.EvaluatedTimeOut;
}
process.AssertPaused();
return this.Result;
} catch (ProcessExitedException) {
throw new GetValueException("Process exited");
}
}
internal void NotifyEvaluationComplete(bool successful)
{
// Eval result should be ICorDebugHandleValue so it should survive Continue()
if (state == EvalState.EvaluatedTimeOut) {
return;
}
if (corEval.GetResult() == null) {
state = EvalState.EvaluatedNoResult;
} else {
if (successful) {
state = EvalState.EvaluatedSuccessfully;
} else {
state = EvalState.EvaluatedException;
}
result = new Value(AppDomain, corEval.GetResult());
}
}
/// <summary> Synchronously calls a function and returns its return value </summary>
public static Value InvokeMethod(DebugMethodInfo method, Value thisValue, Value[] args)
{
if (method.BackingField != null) {
method.Process.TraceMessage("Using backing field for " + method.FullName);
return Value.GetMemberValue(thisValue, method.BackingField, args);
}
return AsyncInvokeMethod(method, thisValue, args).WaitForResult();
}
public static Eval AsyncInvokeMethod(DebugMethodInfo method, Value thisValue, Value[] args)
{
return new Eval(
method.AppDomain,
"Function call: " + method.FullName,
delegate(Eval eval) {
MethodInvokeStarter(eval, method, thisValue, args);
}
);
}
/// <exception cref="GetValueException"><c>GetValueException</c>.</exception>
static void MethodInvokeStarter(Eval eval, DebugMethodInfo method, Value thisValue, Value[] args)
{
List<ICorDebugValue> corArgs = new List<ICorDebugValue>();
args = args ?? new Value[0];
if (args.Length != method.ParameterCount) {
throw new GetValueException("Invalid parameter count");
}
if (!method.IsStatic) {
if (thisValue == null)
throw new GetValueException("'this' is null");
if (thisValue.IsNull)
throw new GetValueException("Null reference");
// if (!(thisValue.IsObject)) // eg Can evaluate on array
if (!method.DeclaringType.IsInstanceOfType(thisValue)) {
throw new GetValueException(
"Can not evaluate because the object is not of proper type. " +
"Expected: " + method.DeclaringType.FullName + " Seen: " + thisValue.Type.FullName
);
}
corArgs.Add(thisValue.CorValue);
}
for(int i = 0; i < args.Length; i++) {
Value arg = args[i];
DebugType paramType = (DebugType)method.GetParameters()[i].ParameterType;
if (!arg.Type.CanImplicitelyConvertTo(paramType))
throw new GetValueException("Inncorrect parameter type");
// Implicitely convert to correct primitve type
if (paramType.IsPrimitive && args[i].Type != paramType) {
object oldPrimVal = arg.PrimitiveValue;
object newPrimVal = Convert.ChangeType(oldPrimVal, paramType.PrimitiveType);
arg = CreateValue(method.AppDomain, newPrimVal);
}
// It is importatnt to pass the parameted in the correct form (boxed/unboxed)
if (paramType.IsValueType) {
corArgs.Add(arg.CorGenericValue);
} else {
if (args[i].Type.IsValueType) {
corArgs.Add(arg.Box().CorValue);
} else {
corArgs.Add(arg.CorValue);
}
}
}
ICorDebugType[] genericArgs = ((DebugType)method.DeclaringType).GenericArgumentsAsCorDebugType;
eval.CorEval2.CallParameterizedFunction(
method.CorFunction,
(uint)genericArgs.Length, genericArgs,
(uint)corArgs.Count, corArgs.ToArray()
);
}
public static Value CreateValue(AppDomain appDomain, object value)
{
if (value == null) {
ICorDebugClass corClass = appDomain.ObjectType.CorType.GetClass();
Thread thread = GetEvaluationThread(appDomain);
ICorDebugEval corEval = thread.CorThread.CreateEval();
ICorDebugValue corValue = corEval.CreateValue((uint)CorElementType.CLASS, corClass);
return new Value(appDomain, corValue);
} else if (value is string) {
return Eval.NewString(appDomain, (string)value);
} else {
if (!value.GetType().IsPrimitive)
throw new DebuggerException("Value must be primitve type. Seen " + value.GetType());
Value val = Eval.NewObjectNoConstructor(DebugType.CreateFromType(appDomain.Mscorlib, value.GetType()));
val.PrimitiveValue = value;
return val;
}
}
/*
// The following function create values only for the purpuse of evalutaion
// They actually do not allocate memory on the managed heap
// The advantage is that it does not continue the process
/// <exception cref="DebuggerException">Can not create string this way</exception>
public static Value CreateValue(Process process, object value)
{
if (value is string) throw new DebuggerException("Can not create string this way");
CorElementType corElemType;
ICorDebugClass corClass = null;
if (value != null) {
corElemType = DebugType.TypeNameToCorElementType(value.GetType().FullName);
} else {
corElemType = CorElementType.CLASS;
corClass = DebugType.Create(process, null, typeof(object).FullName).CorType.Class;
}
ICorDebugEval corEval = CreateCorEval(process);
ICorDebugValue corValue = corEval.CreateValue((uint)corElemType, corClass);
Value v = new Value(process, new Expressions.PrimitiveExpression(value), corValue);
if (value != null) {
v.PrimitiveValue = value;
}
return v;
}
*/
#region Convenience methods
public static Value NewString(AppDomain appDomain, string textToCreate)
{
return AsyncNewString(appDomain, textToCreate).WaitForResult();
}
#endregion
public static Eval AsyncNewString(AppDomain appDomain, string textToCreate)
{
return new Eval(
appDomain,
"New string: " + textToCreate,
delegate(Eval eval) {
eval.CorEval2.NewStringWithLength(textToCreate, (uint)textToCreate.Length);
}
);
}
#region Convenience methods
public static Value NewArray(DebugType type, uint length, uint? lowerBound)
{
return AsyncNewArray(type, length, lowerBound).WaitForResult();
}
#endregion
public static Eval AsyncNewArray(DebugType type, uint length, uint? lowerBound)
{
lowerBound = lowerBound ?? 0;
return new Eval(
type.AppDomain,
"New array: " + type + "[" + length + "]",
delegate(Eval eval) {
// Multi-dimensional arrays not supported in .NET 2.0
eval.CorEval2.NewParameterizedArray(type.CorType, 1, new uint[] { length }, new uint[] { lowerBound.Value });
}
);
}
#region Convenience methods
public static Value NewObject(DebugMethodInfo constructor, Value[] constructorArguments)
{
return AsyncNewObject(constructor, constructorArguments).WaitForResult();
}
#endregion
public static Eval AsyncNewObject(DebugMethodInfo constructor, Value[] constructorArguments)
{
ICorDebugValue[] constructorArgsCorDebug = ValuesAsCorDebug(constructorArguments);
return new Eval(
constructor.AppDomain,
"New object: " + constructor.FullName,
delegate(Eval eval) {
eval.CorEval2.NewParameterizedObject(
constructor.CorFunction,
(uint)constructor.DeclaringType.GetGenericArguments().Length, ((DebugType)constructor.DeclaringType).GenericArgumentsAsCorDebugType,
(uint)constructorArgsCorDebug.Length, constructorArgsCorDebug);
}
);
}
#region Convenience methods
public static Value NewObjectNoConstructor(DebugType debugType)
{
return AsyncNewObjectNoConstructor(debugType).WaitForResult();
}
#endregion
public static Eval AsyncNewObjectNoConstructor(DebugType debugType)
{
return new Eval(
debugType.AppDomain,
"New object: " + debugType.FullName,
delegate(Eval eval) {
eval.CorEval2.NewParameterizedObjectNoConstructor(debugType.CorType.GetClass(), (uint)debugType.GetGenericArguments().Length, debugType.GenericArgumentsAsCorDebugType);
}
);
}
static ICorDebugValue[] ValuesAsCorDebug(Value[] values)
{
ICorDebugValue[] valuesAsCorDebug = new ICorDebugValue[values.Length];
for(int i = 0; i < values.Length; i++) {
valuesAsCorDebug[i] = values[i].CorValue;
}
return valuesAsCorDebug;
}
}
}

23
Debugger/Debugger.Core/EvalCollection.cs

@ -0,0 +1,23 @@ @@ -0,0 +1,23 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using Debugger.Interop.CorDebug;
namespace Debugger
{
public class EvalCollection: CollectionWithEvents<Eval>
{
public EvalCollection(NDebugger debugger): base(debugger) {}
internal Eval this[ICorDebugEval corEval] {
get {
foreach(Eval eval in this) {
if (eval.IsCorEval(corEval)) {
return eval;
}
}
throw new DebuggerException("Eval not found for given ICorDebugEval");
}
}
}
}

121
Debugger/Debugger.Core/Exception.cs

@ -0,0 +1,121 @@ @@ -0,0 +1,121 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System.Text;
namespace Debugger
{
/// <summary> This convenience class provides access to an exception within the debugee. </summary>
/// <seealso cref="System.Exception" />
public class Exception: DebuggerObject
{
Value exception;
public Value Value {
get { return exception; }
}
public Exception(Value exception)
{
this.exception = exception;
}
/// <summary> The <c>GetType().FullName</c> of the exception. </summary>
/// <seealso cref="System.Exception" />
public string Type {
get {
return exception.Type.FullName;
}
}
/// <summary> The <c>Message</c> property of the exception. </summary>
/// <seealso cref="System.Exception" />
public string Message {
get {
Value message = exception.GetMemberValue("_message");
return message.IsNull ? string.Empty : message.AsString();
}
}
/// <summary> The <c>InnerException</c> property of the exception. </summary>
/// <seealso cref="System.Exception" />
public Exception InnerException {
get {
Value innerException = exception.GetMemberValue("_innerException");
return innerException.IsNull ? null : new Exception(innerException);
}
}
public void MakeValuePermanent()
{
exception = exception.GetPermanentReference();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(this.Type);
if (!string.IsNullOrEmpty(this.Message)) {
sb.Append(": ");
sb.Append(this.Message);
}
if (this.InnerException != null) {
sb.Append(" ---> ");
sb.Append(this.InnerException.ToString());
}
return sb.ToString();
}
public string GetStackTrace()
{
return GetStackTrace("--- End of inner exception stack trace ---");
}
/// <summary> Returs formated stacktrace for the exception </summary>
/// <exception cref="GetValueException"> Getting the stacktrace involves property
/// evaluation so GetValueException can be thrown in some cicumstances. </exception>
public string GetStackTrace(string endOfInnerExceptionFormat)
{
StringBuilder sb = new StringBuilder();
if (this.InnerException != null) {
sb.Append(this.InnerException.GetStackTrace(endOfInnerExceptionFormat));
sb.Append(" ");
sb.Append(endOfInnerExceptionFormat);
sb.AppendLine();
}
// Note that evaluation is not possible after a stackoverflow exception
Value stackTrace = exception.GetMemberValue("StackTrace");
if (!stackTrace.IsNull) {
sb.Append(stackTrace.AsString());
sb.AppendLine();
}
return sb.ToString();
}
}
public class ExceptionEventArgs: ProcessEventArgs
{
readonly Exception exception;
readonly ExceptionType exceptionType;
readonly bool isUnhandled;
public Exception Exception {
get { return exception; }
}
public ExceptionType ExceptionType {
get { return exceptionType; }
}
public bool IsUnhandled {
get { return isUnhandled; }
}
public ExceptionEventArgs(Process process, Exception exception, ExceptionType exceptionType, bool isUnhandled):base(process)
{
this.exception = exception;
this.exceptionType = exceptionType;
this.isUnhandled = isUnhandled;
}
}
}

13
Debugger/Debugger.Core/ExceptionType.cs

@ -0,0 +1,13 @@ @@ -0,0 +1,13 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
namespace Debugger
{
public enum ExceptionType
{
FirstChance = 1,
UserFirstChance = 2,
CatchHandlerFound = 3,
Unhandled = 4,
}
}

56
Debugger/Debugger.Core/GetValueException.cs

@ -0,0 +1,56 @@ @@ -0,0 +1,56 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using ICSharpCode.NRefactory.Ast;
namespace Debugger
{
public class GetValueException: DebuggerException
{
INode expression;
string error;
/// <summary> Expression that has caused this exception to occur </summary>
public INode Expression {
get { return expression; }
set { expression = value; }
}
public string Error {
get { return error; }
}
public override string Message {
get {
if (expression == null) {
return error;
} else {
return error;
// return String.Format("Error evaluating \"{0}\": {1}", expression.PrettyPrint(), error);
}
}
}
public GetValueException(INode expression, string error):base(error)
{
this.expression = expression;
this.error = error;
}
public GetValueException(string error, System.Exception inner):base(error, inner)
{
this.error = error;
}
public GetValueException(string errorFmt, params object[] args):base(string.Format(errorFmt, args))
{
this.error = string.Format(errorFmt, args);
}
public GetValueException(string error):base(error)
{
this.error = error;
}
}
}

85
Debugger/Debugger.Core/Interop/Common.cs

@ -0,0 +1,85 @@ @@ -0,0 +1,85 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
#pragma warning disable 108, 1591
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Debugger.Interop
{
// These are used in both CorDebug and CorSym
[StructLayout(LayoutKind.Sequential, Pack=4)]
public struct _FILETIME
{
public uint dwLowDateTime;
public uint dwHighDateTime;
}
[StructLayout(LayoutKind.Sequential, Pack=8)]
public struct _LARGE_INTEGER
{
public long QuadPart;
}
[StructLayout(LayoutKind.Sequential, Pack=8)]
public struct _ULARGE_INTEGER
{
public ulong QuadPart;
}
[ComImport, Guid("0C733A30-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType((short) 1)]
public interface ISequentialStream
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __RemoteRead(out byte pv, [In] uint cb, out uint pcbRead);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __RemoteWrite([In] ref byte pv, [In] uint cb, out uint pcbWritten);
}
[ComImport, InterfaceType((short) 1), Guid("0000000C-0000-0000-C000-000000000046")]
public interface IStream : ISequentialStream
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __RemoteRead(out byte pv, [In] uint cb, out uint pcbRead);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __RemoteWrite([In] ref byte pv, [In] uint cb, out uint pcbWritten);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __RemoteSeek([In] _LARGE_INTEGER dlibMove, [In] uint dwOrigin, out _ULARGE_INTEGER plibNewPosition);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetSize([In] _ULARGE_INTEGER libNewSize);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __RemoteCopyTo([In, MarshalAs(UnmanagedType.Interface)] IStream pstm, [In] _ULARGE_INTEGER cb, out _ULARGE_INTEGER pcbRead, out _ULARGE_INTEGER pcbWritten);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Commit([In] uint grfCommitFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Revert();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __LockRegion([In] _ULARGE_INTEGER libOffset, [In] _ULARGE_INTEGER cb, [In] uint dwLockType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __UnlockRegion([In] _ULARGE_INTEGER libOffset, [In] _ULARGE_INTEGER cb, [In] uint dwLockType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Stat(out tagSTATSTG pstatstg, [In] uint grfStatFlag);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Clone([MarshalAs(UnmanagedType.Interface)] out IStream ppstm);
}
[StructLayout(LayoutKind.Sequential, Pack=8)]
public struct tagSTATSTG
{
[MarshalAs(UnmanagedType.LPWStr)]
public string pwcsName;
public uint type;
public _ULARGE_INTEGER cbSize;
public _FILETIME mtime;
public _FILETIME ctime;
public _FILETIME atime;
public uint grfMode;
public uint grfLocksSupported;
public Guid clsid;
public uint grfStateBits;
public uint reserved;
}
}

1632
Debugger/Debugger.Core/Interop/CorDebug.cs

File diff suppressed because it is too large Load Diff

242
Debugger/Debugger.Core/Interop/CorDebugExtensionMethods.cs

@ -0,0 +1,242 @@ @@ -0,0 +1,242 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Debugger.Interop.CorDebug
{
public static partial class CorDebugExtensionMethods
{
const int EnumerateBufferSize = 16;
static void ProcessOutParameter(object parameter)
{
TrackedComObjects.ProcessOutParameter(parameter);
}
// ICorDebugArrayValue
public static unsafe uint[] GetDimensions(this ICorDebugArrayValue corArray)
{
uint[] dimensions = new uint[corArray.GetRank()];
fixed(uint* pDimensions = dimensions)
corArray.GetDimensions((uint)dimensions.Length, new IntPtr(pDimensions));
return dimensions;
}
public static unsafe uint[] GetBaseIndicies(this ICorDebugArrayValue corArray)
{
uint[] baseIndicies = new uint[corArray.GetRank()];
fixed(uint* pBaseIndicies = baseIndicies)
corArray.GetBaseIndicies((uint)baseIndicies.Length, new IntPtr(pBaseIndicies));
return baseIndicies;
}
public static unsafe ICorDebugValue GetElement(this ICorDebugArrayValue corArray, uint[] indices)
{
fixed(uint* pIndices = indices)
return corArray.GetElement((uint)indices.Length, new IntPtr(pIndices));
}
public static unsafe ICorDebugValue GetElement(this ICorDebugArrayValue corArray, int[] indices)
{
fixed(int* pIndices = indices)
return corArray.GetElement((uint)indices.Length, new IntPtr(pIndices));
}
// ICorDebugClass2
public static ICorDebugType GetParameterizedType(this ICorDebugClass2 corClass, uint elementType, ICorDebugType[] ppTypeArgs)
{
return corClass.GetParameterizedType(elementType, (uint)ppTypeArgs.Length, ppTypeArgs);
}
// ICorDebugCode
public static unsafe byte[] GetCode(this ICorDebugCode corCode)
{
byte[] code = new byte[corCode.GetSize()];
fixed(byte* pCode = code)
corCode.GetCode(0, (uint)code.Length, (uint)code.Length, new IntPtr(pCode));
return code;
}
// ICorDebugEnum
public static IEnumerable<ICorDebugFrame> GetEnumerator(this ICorDebugFrameEnum corEnum)
{
corEnum.Reset();
while (true) {
ICorDebugFrame[] corFrames = new ICorDebugFrame[EnumerateBufferSize];
uint fetched = corEnum.Next(EnumerateBufferSize, corFrames);
if (fetched == 0)
yield break;
for(int i = 0; i < fetched; i++)
yield return corFrames[i];
}
}
public static ICorDebugFrame Next(this ICorDebugFrameEnum corEnum)
{
ICorDebugFrame[] corFrames = new ICorDebugFrame[] { null };
uint framesFetched = corEnum.Next(1, corFrames);
return corFrames[0];
}
public static IEnumerable<ICorDebugChain> GetEnumerator(this ICorDebugChainEnum corEnum)
{
corEnum.Reset();
while (true) {
ICorDebugChain[] corChains = new ICorDebugChain[EnumerateBufferSize];
uint fetched = corEnum.Next(EnumerateBufferSize, corChains);
if (fetched == 0)
yield break;
for(int i = 0; i < fetched; i++)
yield return corChains[i];
}
}
public static ICorDebugChain Next(this ICorDebugChainEnum corChainEnum)
{
ICorDebugChain[] corChains = new ICorDebugChain[] { null };
uint chainsFetched = corChainEnum.Next(1, corChains);
return corChains[0];
}
// ICorDebugGenericValue
public static unsafe Byte[] GetRawValue(this ICorDebugGenericValue corGenVal)
{
byte[] retValue = new byte[(int)corGenVal.GetSize()];
fixed(byte* pRetValue = retValue)
corGenVal.GetValue(new IntPtr(pRetValue));
return retValue;
}
public static unsafe void SetRawValue(this ICorDebugGenericValue corGenVal, byte[] value)
{
if (corGenVal.GetSize() != value.Length)
throw new ArgumentException("Incorrect length");
fixed(byte* pValue = value)
corGenVal.SetValue(new IntPtr(pValue));
}
public static unsafe object GetValue(this ICorDebugGenericValue corGenVal, Type type)
{
object retValue;
byte[] value = new byte[(int)corGenVal.GetSize()];
fixed(byte* pValue = value) {
corGenVal.GetValue(new IntPtr(pValue));
switch(type.FullName) {
case "System.Boolean": retValue = *((System.Boolean*)pValue); break;
case "System.Char": retValue = *((System.Char*) pValue); break;
case "System.SByte": retValue = *((System.SByte*) pValue); break;
case "System.Byte": retValue = *((System.Byte*) pValue); break;
case "System.Int16": retValue = *((System.Int16*) pValue); break;
case "System.UInt16": retValue = *((System.UInt16*) pValue); break;
case "System.Int32": retValue = *((System.Int32*) pValue); break;
case "System.UInt32": retValue = *((System.UInt32*) pValue); break;
case "System.Int64": retValue = *((System.Int64*) pValue); break;
case "System.UInt64": retValue = *((System.UInt64*) pValue); break;
case "System.Single": retValue = *((System.Single*) pValue); break;
case "System.Double": retValue = *((System.Double*) pValue); break;
case "System.IntPtr": retValue = *((System.IntPtr*) pValue); break;
case "System.UIntPtr": retValue = *((System.UIntPtr*)pValue); break;
default: throw new NotSupportedException();
}
}
return retValue;
}
public static unsafe void SetValue(this ICorDebugGenericValue corGenVal, object value)
{
if (value == null)
throw new ArgumentNullException("value");
byte[] val = new byte[(int)corGenVal.GetSize()];
fixed(byte* pValue = val) {
switch(value.GetType().FullName) {
case "System.Boolean": *((System.Boolean*)pValue) = (System.Boolean)value; break;
case "System.Char": *((System.Char*) pValue) = (System.Char) value; break;
case "System.SByte": *((System.SByte*) pValue) = (System.SByte) value; break;
case "System.Byte": *((System.Byte*) pValue) = (System.Byte) value; break;
case "System.Int16": *((System.Int16*) pValue) = (System.Int16) value; break;
case "System.UInt16": *((System.UInt16*) pValue) = (System.UInt16) value; break;
case "System.Int32": *((System.Int32*) pValue) = (System.Int32) value; break;
case "System.UInt32": *((System.UInt32*) pValue) = (System.UInt32) value; break;
case "System.Int64": *((System.Int64*) pValue) = (System.Int64) value; break;
case "System.UInt64": *((System.UInt64*) pValue) = (System.UInt64) value; break;
case "System.Single": *((System.Single*) pValue) = (System.Single) value; break;
case "System.Double": *((System.Double*) pValue) = (System.Double) value; break;
case "System.IntPtr": *((System.IntPtr*) pValue) = (System.IntPtr) value; break;
case "System.UIntPtr": *((System.UIntPtr*)pValue) = (System.UIntPtr)value; break;
default: throw new NotSupportedException();
}
corGenVal.SetValue(new IntPtr(pValue));
}
}
// ICorDebugModule
public static string GetName(this ICorDebugModule corModule)
{
// The 'out' parameter returns the size of the needed buffer as in other functions
return Util.GetString(corModule.GetName, 256, true);
}
// ICorDebugProcess
public static bool HasQueuedCallbacks(this ICorDebugProcess corProcess)
{
return corProcess.HasQueuedCallbacks(null) != 0;
}
// ICorDebugStepper
public static unsafe void StepRange(this ICorDebugStepper corStepper, bool bStepIn, int[] ranges)
{
fixed(int* pRanges = ranges)
corStepper.StepRange(bStepIn?1:0, (IntPtr)pRanges, (uint)ranges.Length / 2);
}
// ICorDebugStringValue
public static string GetString(this ICorDebugStringValue corString)
{
uint length = corString.GetLength();
return Util.GetString(corString.GetString, length, false);
}
// ICorDebugTypeEnum
public static IEnumerable<ICorDebugType> GetEnumerator(this ICorDebugTypeEnum corTypeEnum)
{
corTypeEnum.Reset();
while (true) {
ICorDebugType corType = corTypeEnum.Next();
if (corType != null) {
yield return corType;
} else {
break;
}
}
}
public static ICorDebugType Next(this ICorDebugTypeEnum corTypeEnum)
{
ICorDebugType[] corTypes = new ICorDebugType[1];
uint typesFetched = corTypeEnum.Next(1, corTypes);
if (typesFetched == 0) {
return null;
} else {
return corTypes[0];
}
}
public static List<ICorDebugType> ToList(this ICorDebugTypeEnum corTypeEnum)
{
return new List<ICorDebugType>(corTypeEnum.GetEnumerator());
}
}
}

3342
Debugger/Debugger.Core/Interop/CorDebugExtensionMethods.generated.cs

File diff suppressed because it is too large Load Diff

138
Debugger/Debugger.Core/Interop/CorPublish.cs

@ -0,0 +1,138 @@ @@ -0,0 +1,138 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
#pragma warning disable 108, 1591
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace Debugger.Interop.CorPublish
{
[ComImport, TypeLibType((short) 2), ClassInterface((short) 0), Guid("047A9A40-657E-11D3-8D5B-00104B35E7EF")]
public class CorpubPublishClass : ICorPublish, CorpubPublish, ICorPublishProcess, ICorPublishAppDomain, ICorPublishProcessEnum, ICorPublishAppDomainEnum
{
// Methods
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Clone([MarshalAs(UnmanagedType.Interface)] out ICorPublishEnum ppEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __EnumAppDomains([MarshalAs(UnmanagedType.Interface)] out ICorPublishAppDomainEnum ppEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __EnumProcesses([In, ComAliasName("CorpubProcessLib.COR_PUB_ENUMPROCESS")] COR_PUB_ENUMPROCESS Type, [MarshalAs(UnmanagedType.Interface)] out ICorPublishProcessEnum ppIEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetCount(out uint pcelt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetDisplayName([In] uint cchName, out uint pcchName, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetID(out uint puId);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetName([In] uint cchName, out uint pcchName, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetProcess([In] uint pid, [MarshalAs(UnmanagedType.Interface)] out ICorPublishProcess ppProcess);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetProcessID(out uint pid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __ICorPublishAppDomainEnum_Clone([MarshalAs(UnmanagedType.Interface)] out ICorPublishEnum ppEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __ICorPublishAppDomainEnum_GetCount(out uint pcelt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __ICorPublishAppDomainEnum_Reset();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __ICorPublishAppDomainEnum_Skip([In] uint celt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __IsManaged(out int pbManaged);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Next([In] uint celt, [MarshalAs(UnmanagedType.Interface)] out ICorPublishAppDomain objects, out uint pceltFetched);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Next([In] uint celt, [MarshalAs(UnmanagedType.Interface)] out ICorPublishProcess objects, out uint pceltFetched);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Reset();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Skip([In] uint celt);
}
[ComImport, CoClass(typeof(CorpubPublishClass)), Guid("9613A0E7-5A68-11D3-8F84-00A0C9B4D50C")]
public interface CorpubPublish : ICorPublish
{
}
public enum COR_PUB_ENUMPROCESS
{
COR_PUB_MANAGEDONLY = 1
}
[ComImport, Guid("9613A0E7-5A68-11D3-8F84-00A0C9B4D50C"), InterfaceType((short) 1)]
public interface ICorPublish
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __EnumProcesses([In, ComAliasName("CorpubProcessLib.COR_PUB_ENUMPROCESS")] COR_PUB_ENUMPROCESS Type, [MarshalAs(UnmanagedType.Interface)] out ICorPublishProcessEnum ppIEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetProcess([In] uint pid, [MarshalAs(UnmanagedType.Interface)] out ICorPublishProcess ppProcess);
}
[ComImport, Guid("D6315C8F-5A6A-11D3-8F84-00A0C9B4D50C"), InterfaceType((short) 1)]
public interface ICorPublishAppDomain
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetID(out uint puId);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetName([In] uint cchName, out uint pcchName, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szName);
}
[ComImport, Guid("9F0C98F5-5A6A-11D3-8F84-00A0C9B4D50C"), InterfaceType((short) 1),]
public interface ICorPublishAppDomainEnum : ICorPublishEnum
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Skip([In] uint celt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Reset();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Clone([MarshalAs(UnmanagedType.Interface)] out ICorPublishEnum ppEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetCount(out uint pcelt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Next([In] uint celt, [MarshalAs(UnmanagedType.Interface)] out ICorPublishAppDomain objects, out uint pceltFetched);
}
[ComImport, Guid("C0B22967-5A69-11D3-8F84-00A0C9B4D50C"), InterfaceType((short) 1)]
public interface ICorPublishEnum
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Skip([In] uint celt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Reset();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Clone([MarshalAs(UnmanagedType.Interface)] out ICorPublishEnum ppEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetCount(out uint pcelt);
}
[ComImport, Guid("18D87AF1-5A6A-11D3-8F84-00A0C9B4D50C"), InterfaceType((short) 1)]
public interface ICorPublishProcess
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __IsManaged(out int pbManaged);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __EnumAppDomains([MarshalAs(UnmanagedType.Interface)] out ICorPublishAppDomainEnum ppEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetProcessID(out uint pid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetDisplayName([In] uint cchName, out uint pcchName, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szName);
}
[ComImport, Guid("A37FBD41-5A69-11D3-8F84-00A0C9B4D50C"), InterfaceType((short) 1)]
public interface ICorPublishProcessEnum : ICorPublishEnum
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Skip([In] uint celt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Reset();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Clone([MarshalAs(UnmanagedType.Interface)] out ICorPublishEnum ppEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetCount(out uint pcelt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Next([In] uint celt, [MarshalAs(UnmanagedType.Interface)] out ICorPublishProcess objects, out uint pceltFetched);
}
}

15
Debugger/Debugger.Core/Interop/CorPublishExtensionMethods.cs

@ -0,0 +1,15 @@ @@ -0,0 +1,15 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
namespace Debugger.Interop.CorPublish
{
public static partial class CorPublishExtensionMethods
{
static void ProcessOutParameter(object parameter)
{
TrackedComObjects.ProcessOutParameter(parameter);
}
}
}

273
Debugger/Debugger.Core/Interop/CorPublishExtensionMethods.generated.cs

@ -0,0 +1,273 @@ @@ -0,0 +1,273 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace Debugger.Interop.CorPublish
{
public static partial class CorPublishExtensionMethods
{
public static ICorPublishEnum Clone(this CorpubPublishClass instance)
{
ICorPublishEnum ppEnum;
instance.__Clone(out ppEnum);
ProcessOutParameter(ppEnum);
return ppEnum;
}
public static ICorPublishAppDomainEnum EnumAppDomains(this CorpubPublishClass instance)
{
ICorPublishAppDomainEnum ppEnum;
instance.__EnumAppDomains(out ppEnum);
ProcessOutParameter(ppEnum);
return ppEnum;
}
public static ICorPublishProcessEnum EnumProcesses(this CorpubPublishClass instance, COR_PUB_ENUMPROCESS Type)
{
ICorPublishProcessEnum ppIEnum;
instance.__EnumProcesses(Type, out ppIEnum);
ProcessOutParameter(ppIEnum);
return ppIEnum;
}
public static uint GetCount(this CorpubPublishClass instance)
{
uint pcelt;
instance.__GetCount(out pcelt);
return pcelt;
}
public static void GetDisplayName(this CorpubPublishClass instance, uint cchName, out uint pcchName, StringBuilder szName)
{
instance.__GetDisplayName(cchName, out pcchName, szName);
}
public static uint GetID(this CorpubPublishClass instance)
{
uint puId;
instance.__GetID(out puId);
return puId;
}
public static void GetName(this CorpubPublishClass instance, uint cchName, out uint pcchName, StringBuilder szName)
{
instance.__GetName(cchName, out pcchName, szName);
}
public static ICorPublishProcess GetProcess(this CorpubPublishClass instance, uint pid)
{
ICorPublishProcess ppProcess;
instance.__GetProcess(pid, out ppProcess);
ProcessOutParameter(ppProcess);
return ppProcess;
}
public static uint GetProcessID(this CorpubPublishClass instance)
{
uint pid;
instance.__GetProcessID(out pid);
return pid;
}
public static ICorPublishEnum ICorPublishAppDomainEnum_Clone(this CorpubPublishClass instance)
{
ICorPublishEnum ppEnum;
instance.__ICorPublishAppDomainEnum_Clone(out ppEnum);
ProcessOutParameter(ppEnum);
return ppEnum;
}
public static uint ICorPublishAppDomainEnum_GetCount(this CorpubPublishClass instance)
{
uint pcelt;
instance.__ICorPublishAppDomainEnum_GetCount(out pcelt);
return pcelt;
}
public static void ICorPublishAppDomainEnum_Reset(this CorpubPublishClass instance)
{
instance.__ICorPublishAppDomainEnum_Reset();
}
public static void ICorPublishAppDomainEnum_Skip(this CorpubPublishClass instance, uint celt)
{
instance.__ICorPublishAppDomainEnum_Skip(celt);
}
public static int IsManaged(this CorpubPublishClass instance)
{
int pbManaged;
instance.__IsManaged(out pbManaged);
return pbManaged;
}
public static void Next(this CorpubPublishClass instance, uint celt, out ICorPublishAppDomain objects, out uint pceltFetched)
{
instance.__Next(celt, out objects, out pceltFetched);
ProcessOutParameter(objects);
}
public static void Next(this CorpubPublishClass instance, uint celt, out ICorPublishProcess objects, out uint pceltFetched)
{
instance.__Next(celt, out objects, out pceltFetched);
ProcessOutParameter(objects);
}
public static void Reset(this CorpubPublishClass instance)
{
instance.__Reset();
}
public static void Skip(this CorpubPublishClass instance, uint celt)
{
instance.__Skip(celt);
}
public static ICorPublishProcessEnum EnumProcesses(this ICorPublish instance, COR_PUB_ENUMPROCESS Type)
{
ICorPublishProcessEnum ppIEnum;
instance.__EnumProcesses(Type, out ppIEnum);
ProcessOutParameter(ppIEnum);
return ppIEnum;
}
public static ICorPublishProcess GetProcess(this ICorPublish instance, uint pid)
{
ICorPublishProcess ppProcess;
instance.__GetProcess(pid, out ppProcess);
ProcessOutParameter(ppProcess);
return ppProcess;
}
public static uint GetID(this ICorPublishAppDomain instance)
{
uint puId;
instance.__GetID(out puId);
return puId;
}
public static void GetName(this ICorPublishAppDomain instance, uint cchName, out uint pcchName, StringBuilder szName)
{
instance.__GetName(cchName, out pcchName, szName);
}
public static void Skip(this ICorPublishAppDomainEnum instance, uint celt)
{
instance.__Skip(celt);
}
public static void Reset(this ICorPublishAppDomainEnum instance)
{
instance.__Reset();
}
public static ICorPublishEnum Clone(this ICorPublishAppDomainEnum instance)
{
ICorPublishEnum ppEnum;
instance.__Clone(out ppEnum);
ProcessOutParameter(ppEnum);
return ppEnum;
}
public static uint GetCount(this ICorPublishAppDomainEnum instance)
{
uint pcelt;
instance.__GetCount(out pcelt);
return pcelt;
}
public static void Next(this ICorPublishAppDomainEnum instance, uint celt, out ICorPublishAppDomain objects, out uint pceltFetched)
{
instance.__Next(celt, out objects, out pceltFetched);
ProcessOutParameter(objects);
}
public static void Skip(this ICorPublishEnum instance, uint celt)
{
instance.__Skip(celt);
}
public static void Reset(this ICorPublishEnum instance)
{
instance.__Reset();
}
public static ICorPublishEnum Clone(this ICorPublishEnum instance)
{
ICorPublishEnum ppEnum;
instance.__Clone(out ppEnum);
ProcessOutParameter(ppEnum);
return ppEnum;
}
public static uint GetCount(this ICorPublishEnum instance)
{
uint pcelt;
instance.__GetCount(out pcelt);
return pcelt;
}
public static int IsManaged(this ICorPublishProcess instance)
{
int pbManaged;
instance.__IsManaged(out pbManaged);
return pbManaged;
}
public static ICorPublishAppDomainEnum EnumAppDomains(this ICorPublishProcess instance)
{
ICorPublishAppDomainEnum ppEnum;
instance.__EnumAppDomains(out ppEnum);
ProcessOutParameter(ppEnum);
return ppEnum;
}
public static uint GetProcessID(this ICorPublishProcess instance)
{
uint pid;
instance.__GetProcessID(out pid);
return pid;
}
public static void GetDisplayName(this ICorPublishProcess instance, uint cchName, out uint pcchName, StringBuilder szName)
{
instance.__GetDisplayName(cchName, out pcchName, szName);
}
public static void Skip(this ICorPublishProcessEnum instance, uint celt)
{
instance.__Skip(celt);
}
public static void Reset(this ICorPublishProcessEnum instance)
{
instance.__Reset();
}
public static ICorPublishEnum Clone(this ICorPublishProcessEnum instance)
{
ICorPublishEnum ppEnum;
instance.__Clone(out ppEnum);
ProcessOutParameter(ppEnum);
return ppEnum;
}
public static uint GetCount(this ICorPublishProcessEnum instance)
{
uint pcelt;
instance.__GetCount(out pcelt);
return pcelt;
}
public static void Next(this ICorPublishProcessEnum instance, uint celt, out ICorPublishProcess objects, out uint pceltFetched)
{
instance.__Next(celt, out objects, out pceltFetched);
ProcessOutParameter(objects);
}
}
}

523
Debugger/Debugger.Core/Interop/CorSym.cs

@ -0,0 +1,523 @@ @@ -0,0 +1,523 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
#pragma warning disable 108, 1591
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Debugger.Interop.CorSym
{
public enum CorSymAddrKind
{
// Fields
ADDR_BITFIELD = 9,
ADDR_IL_OFFSET = 1,
ADDR_NATIVE_ISECTOFFSET = 10,
ADDR_NATIVE_OFFSET = 5,
ADDR_NATIVE_REGISTER = 3,
ADDR_NATIVE_REGREG = 6,
ADDR_NATIVE_REGREL = 4,
ADDR_NATIVE_REGSTK = 7,
ADDR_NATIVE_RVA = 2,
ADDR_NATIVE_STKREG = 8
}
[ComImport, CoClass(typeof(CorSymBinder_SxSClass)), Guid("AA544D42-28CB-11D3-BD22-0000F80849BD")]
public interface CorSymBinder_SxS : ISymUnmanagedBinder
{
}
[ComImport, Guid("0A29FF9E-7F9C-4437-8B11-F424491E3931"), ClassInterface((short) 0), TypeLibType((short) 2)]
public class CorSymBinder_SxSClass : ISymUnmanagedBinder, CorSymBinder_SxS
{
// Methods
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), PreserveSig]
public virtual extern int __GetReaderForFile([In, MarshalAs(UnmanagedType.IUnknown)] object importer, [In] IntPtr filename, [In] IntPtr searchPath, [Out, In, MarshalAs(UnmanagedType.IUnknown)] ref object retVal);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern ISymUnmanagedReader __GetReaderFromStream([In, MarshalAs(UnmanagedType.IUnknown)] object importer, [In, MarshalAs(UnmanagedType.Interface)] IStream pstream);
}
[ComImport, CoClass(typeof(CorSymReader_SxSClass)), Guid("B4CE6286-2A6B-3712-A3B7-1EE1DAD467B5")]
public interface CorSymReader_SxS : ISymUnmanagedReader
{
}
[ComImport, Guid("0A3976C5-4529-4EF8-B0B0-42EED37082CD"), TypeLibType((short) 2), ClassInterface((short) 0), ComConversionLoss]
public class CorSymReader_SxSClass : ISymUnmanagedReader, CorSymReader_SxS
{
// Methods
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern ISymUnmanagedDocument __GetDocument([In] IntPtr url, [In] Guid language, [In] Guid languageVendor, [In] Guid documentType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetDocuments([In] uint cDocs, out uint pcDocs, [Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedDocument[] pDocs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetDocumentVersion([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocument pDoc, out int version, out int pbCurrent);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetGlobalVariables([In] uint cVars, out uint pcVars, [Out] IntPtr pVars);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern ISymUnmanagedMethod __GetMethod([In] uint token);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern ISymUnmanagedMethod __GetMethodByVersion([In] uint token, [In] int version);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern ISymUnmanagedMethod __GetMethodFromDocumentPosition([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocument document, [In] uint line, [In] uint column);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetMethodsFromDocumentPosition([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocument document, [In] uint line, [In] uint column, [In] uint cMethod, out uint pcMethod, [Out] IntPtr pRetVal);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetMethodVersion([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedMethod pMethod, out int version);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetNamespaces([In] uint cNameSpaces, out uint pcNameSpaces, [Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedNamespace[] namespaces);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetSymAttribute([In] uint parent, [In] IntPtr name, [In] uint cBuffer, out uint pcBuffer, [Out] IntPtr buffer);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetSymbolStoreFileName([In] uint cchName, out uint pcchName, [Out] IntPtr szName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern uint __GetUserEntryPoint();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetVariables([In] uint parent, [In] uint cVars, out uint pcVars, [Out] IntPtr pVars);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Initialize([In, MarshalAs(UnmanagedType.IUnknown)] object importer, [In] IntPtr filename, [In] IntPtr searchPath, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __ReplaceSymbolStore([In] IntPtr filename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __UpdateSymbolStore([In] IntPtr filename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream);
}
public enum CorSymSearchPolicyAttributes
{
// Fields
AllowOriginalPathAccess = 4,
AllowReferencePathAccess = 8,
AllowRegistryAccess = 1,
AllowSymbolServerAccess = 2
}
public enum CorSymVarFlag
{
// Fields
VAR_IS_COMP_GEN = 1
}
[ComImport, CoClass(typeof(CorSymWriter_SxSClass)), Guid("ED14AA72-78E2-4884-84E2-334293AE5214")]
public interface CorSymWriter_SxS : ISymUnmanagedWriter
{
}
[ComImport, TypeLibType((short) 2), Guid("0AE2DEB0-F901-478B-BB9F-881EE8066788"), ClassInterface((short) 0), ComConversionLoss]
public class CorSymWriter_SxSClass : ISymUnmanagedWriter, CorSymWriter_SxS
{
// Methods
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Abort();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Close();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __CloseMethod();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __CloseNamespace();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __CloseScope([In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __DefineConstant([In] IntPtr name, [In, MarshalAs(UnmanagedType.Struct)] object value, [In] uint cSig, [In] ref byte signature);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern ISymUnmanagedDocumentWriter __DefineDocument([In] IntPtr url, [In] ref Guid language, [In] ref Guid languageVendor, [In] ref Guid documentType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __DefineField([In] uint parent, [In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __DefineGlobalVariable([In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __DefineLocalVariable([In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3, [In] uint startOffset, [In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __DefineParameter([In] IntPtr name, [In] uint attributes, [In] uint sequence, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __DefineSequencePoints([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] uint spCount, [In] ref uint offsets, [In] ref uint lines, [In] ref uint columns, [In] ref uint endLines, [In] ref uint endColumns);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __GetDebugInfo([In] ref uint pIDD, [In] uint cData, out uint pcData, [Out] IntPtr data);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Initialize([In, MarshalAs(UnmanagedType.IUnknown)] object emitter, [In] IntPtr filename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream, [In] int fFullBuild);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __Initialize2([In, MarshalAs(UnmanagedType.IUnknown)] object emitter, [In] IntPtr tempfilename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream, [In] int fFullBuild, [In] IntPtr finalfilename);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __OpenMethod([In] uint method);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __OpenNamespace([In] IntPtr name);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern uint __OpenScope([In] uint startOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __RemapToken([In] uint oldToken, [In] uint newToken);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __SetMethodSourceRange([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter startDoc, [In] uint startLine, [In] uint startColumn, [In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter endDoc, [In] uint endLine, [In] uint endColumn);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __SetScopeRange([In] uint scopeID, [In] uint startOffset, [In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __SetSymAttribute([In] uint parent, [In] IntPtr name, [In] uint cData, [In] ref byte data);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __SetUserEntryPoint([In] uint entryMethod);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
public virtual extern void __UsingNamespace([In] IntPtr fullName);
}
[ComImport, InterfaceType((short) 1), Guid("AA544D42-28CB-11D3-BD22-0000F80849BD")]
public interface ISymUnmanagedBinder
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), PreserveSig]
int __GetReaderForFile([In, MarshalAs(UnmanagedType.IUnknown)] object importer, [In] IntPtr filename, [In] IntPtr searchPath, [Out, In, MarshalAs(UnmanagedType.IUnknown)] ref object retVal);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedReader __GetReaderFromStream([In, MarshalAs(UnmanagedType.IUnknown)] object importer, [In, MarshalAs(UnmanagedType.Interface)] IStream pstream);
}
[ComImport, InterfaceType((short) 1), Guid("969708D2-05E5-4861-A3B0-96E473CDF63F")]
public interface ISymUnmanagedDispose
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Destroy();
}
[ComImport, Guid("40DE4037-7C81-3E1E-B022-AE1ABFF2CA08"), ComConversionLoss, InterfaceType((short) 1)]
public interface ISymUnmanagedDocument
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetURL([In] uint cchUrl, out uint pcchUrl, [Out] IntPtr szUrl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
Guid __GetDocumentType();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
Guid __GetLanguage();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
Guid __GetLanguageVendor();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
Guid __GetCheckSumAlgorithmId();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetCheckSum([In] uint cData, out uint pcData, [Out] IntPtr data);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __FindClosestLine([In] uint line);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
int __HasEmbeddedSource();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetSourceLength();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSourceRange([In] uint startLine, [In] uint startColumn, [In] uint endLine, [In] uint endColumn, [In] uint cSourceBytes, out uint pcSourceBytes, [Out] IntPtr source);
}
[ComImport, Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006"), InterfaceType((short) 1)]
public interface ISymUnmanagedDocumentWriter
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetSource([In] uint sourceSize, [In] ref byte source);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetCheckSum([In] Guid algorithmId, [In] uint checkSumSize, [In] ref byte checkSum);
}
[ComImport, InterfaceType((short) 1), ComConversionLoss, Guid("B62B923C-B500-3158-A543-24F307A8B7E1")]
public interface ISymUnmanagedMethod
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetToken();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetSequencePointCount();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedScope __GetRootScope();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedScope __GetScopeFromOffset([In] uint offset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetOffset([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocument document, [In] uint line, [In] uint column);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetRanges([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocument document, [In] uint line, [In] uint column, [In] uint cRanges, out uint pcRanges, [Out] IntPtr ranges);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetParameters([In] uint cParams, out uint pcParams, [Out] IntPtr @params);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetNamespace([MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedNamespace pRetVal);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSourceStartEnd([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0, SizeConst=2)] ISymUnmanagedDocument[] docs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0, SizeConst=2)] uint[] lines, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0, SizeConst=2)] uint[] columns, out int pRetVal);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSequencePoints([In] uint cPoints, out uint pcPoints, [Out, MarshalAs(UnmanagedType.LPArray)] uint[] offsets, [Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedDocument[] documents, [Out, MarshalAs(UnmanagedType.LPArray)] uint[] lines, [Out, MarshalAs(UnmanagedType.LPArray)] uint[] columns, [Out, MarshalAs(UnmanagedType.LPArray)] uint[] endLines, [Out, MarshalAs(UnmanagedType.LPArray)] uint[] endColumns);
}
[ComImport, InterfaceType((short) 1), ComConversionLoss, Guid("0DFF7289-54F8-11D3-BD28-0000F80849BD")]
public interface ISymUnmanagedNamespace
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetName([In] uint cchName, out uint pcchName, [Out] IntPtr szName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetNamespaces([In] uint cNameSpaces, out uint pcNameSpaces, [Out] IntPtr namespaces);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetVariables([In] uint cVars, out uint pcVars, [Out] IntPtr pVars);
}
[ComImport, InterfaceType((short) 1), ComConversionLoss, Guid("B4CE6286-2A6B-3712-A3B7-1EE1DAD467B5")]
public interface ISymUnmanagedReader
{
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedDocument __GetDocument([In] IntPtr url, [In] Guid language, [In] Guid languageVendor, [In] Guid documentType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetDocuments([In] uint cDocs, out uint pcDocs, [Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedDocument[] pDocs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetUserEntryPoint();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedMethod __GetMethod([In] uint token);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedMethod __GetMethodByVersion([In] uint token, [In] int version);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetVariables([In] uint parent, [In] uint cVars, out uint pcVars, [Out] IntPtr pVars);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetGlobalVariables([In] uint cVars, out uint pcVars, [Out] IntPtr pVars);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedMethod __GetMethodFromDocumentPosition([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocument document, [In] uint line, [In] uint column);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSymAttribute([In] uint parent, [In] IntPtr name, [In] uint cBuffer, out uint pcBuffer, [Out] IntPtr buffer);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetNamespaces([In] uint cNameSpaces, out uint pcNameSpaces, [Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedNamespace[] namespaces);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Initialize([In, MarshalAs(UnmanagedType.IUnknown)] object importer, [In] IntPtr filename, [In] IntPtr searchPath, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __UpdateSymbolStore([In] IntPtr filename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __ReplaceSymbolStore([In] IntPtr filename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSymbolStoreFileName([In] uint cchName, out uint pcchName, [Out] IntPtr szName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetMethodsFromDocumentPosition([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocument document, [In] uint line, [In] uint column, [In] uint cMethod, out uint pcMethod, [Out] IntPtr pRetVal);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetDocumentVersion([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocument pDoc, out int version, out int pbCurrent);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetMethodVersion([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedMethod pMethod, out int version);
}
[ComImport, Guid("20D9645D-03CD-4E34-9C11-9848A5B084F1"), InterfaceType((short) 1)]
public interface ISymUnmanagedReaderSymbolSearchInfo
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSymbolSearchInfoCount(out uint pcSearchInfo);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSymbolSearchInfo([In] uint cSearchInfo, out uint pcSearchInfo, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedSymbolSearchInfo rgpSearchInfo);
}
[ComImport, Guid("68005D0F-B8E0-3B01-84D5-A11A94154942"), ComConversionLoss, InterfaceType((short) 1)]
public interface ISymUnmanagedScope
{
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedMethod __GetMethod();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedScope __GetParent();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetChildren([In] uint cChildren, out uint pcChildren, [Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedScope[] children);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetStartOffset();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetEndOffset();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetLocalCount();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetLocals([In] uint cLocals, out uint pcLocals, [Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedVariable[] locals);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetNamespaces([In] uint cNameSpaces, out uint pcNameSpaces, [Out, MarshalAs(UnmanagedType.LPArray)] ISymUnmanagedNamespace[] namespaces);
}
[ComImport, ComConversionLoss, InterfaceType((short) 1), Guid("F8B3534A-A46B-4980-B520-BEC4ACEABA8F")]
public interface ISymUnmanagedSymbolSearchInfo
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSearchPathLength(out uint pcchPath);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSearchPath([In] uint cchPath, out uint pcchPath, [Out] IntPtr szPath);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetHRESULT([MarshalAs(UnmanagedType.Error)] out int phr);
}
[ComImport, Guid("9F60EEBE-2D9A-3F7C-BF58-80BC991C60BB"), InterfaceType((short) 1), ComConversionLoss]
public interface ISymUnmanagedVariable
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetName([In] uint cchName, out uint pcchName, [In] IntPtr szName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetAttributes();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetSignature([In] uint cSig, out uint pcSig, [In] IntPtr sig);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetAddressKind();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetAddressField1();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetAddressField2();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetAddressField3();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetStartOffset();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __GetEndOffset();
}
[ComImport, ComConversionLoss, InterfaceType((short) 1), Guid("ED14AA72-78E2-4884-84E2-334293AE5214")]
public interface ISymUnmanagedWriter
{
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedDocumentWriter __DefineDocument([In] IntPtr url, [In] ref Guid language, [In] ref Guid languageVendor, [In] ref Guid documentType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetUserEntryPoint([In] uint entryMethod);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __OpenMethod([In] uint method);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __CloseMethod();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __OpenScope([In] uint startOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __CloseScope([In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetScopeRange([In] uint scopeID, [In] uint startOffset, [In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineLocalVariable([In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3, [In] uint startOffset, [In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineParameter([In] IntPtr name, [In] uint attributes, [In] uint sequence, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineField([In] uint parent, [In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineGlobalVariable([In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Close();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetSymAttribute([In] uint parent, [In] IntPtr name, [In] uint cData, [In] ref byte data);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __OpenNamespace([In] IntPtr name);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __CloseNamespace();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __UsingNamespace([In] IntPtr fullName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetMethodSourceRange([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter startDoc, [In] uint startLine, [In] uint startColumn, [In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter endDoc, [In] uint endLine, [In] uint endColumn);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Initialize([In, MarshalAs(UnmanagedType.IUnknown)] object emitter, [In] IntPtr filename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream, [In] int fFullBuild);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetDebugInfo([In] ref uint pIDD, [In] uint cData, out uint pcData, [Out] IntPtr data);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineSequencePoints([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] uint spCount, [In] ref uint offsets, [In] ref uint lines, [In] ref uint columns, [In] ref uint endLines, [In] ref uint endColumns);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __RemapToken([In] uint oldToken, [In] uint newToken);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Initialize2([In, MarshalAs(UnmanagedType.IUnknown)] object emitter, [In] IntPtr tempfilename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream, [In] int fFullBuild, [In] IntPtr finalfilename);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineConstant([In] IntPtr name, [In, MarshalAs(UnmanagedType.Struct)] object value, [In] uint cSig, [In] ref byte signature);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Abort();
}
[ComImport, Guid("0B97726E-9E6D-4F05-9A26-424022093CAA"), InterfaceType((short) 1)]
public interface ISymUnmanagedWriter2 : ISymUnmanagedWriter
{
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
ISymUnmanagedDocumentWriter __DefineDocument([In] IntPtr url, [In] ref Guid language, [In] ref Guid languageVendor, [In] ref Guid documentType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetUserEntryPoint([In] uint entryMethod);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __OpenMethod([In] uint method);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __CloseMethod();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
uint __OpenScope([In] uint startOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __CloseScope([In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetScopeRange([In] uint scopeID, [In] uint startOffset, [In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineLocalVariable([In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3, [In] uint startOffset, [In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineParameter([In] IntPtr name, [In] uint attributes, [In] uint sequence, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineField([In] uint parent, [In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineGlobalVariable([In] IntPtr name, [In] uint attributes, [In] uint cSig, [In] ref byte signature, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Close();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetSymAttribute([In] uint parent, [In] IntPtr name, [In] uint cData, [In] ref byte data);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __OpenNamespace([In] IntPtr name);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __CloseNamespace();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __UsingNamespace([In] IntPtr fullName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __SetMethodSourceRange([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter startDoc, [In] uint startLine, [In] uint startColumn, [In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter endDoc, [In] uint endLine, [In] uint endColumn);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Initialize([In, MarshalAs(UnmanagedType.IUnknown)] object emitter, [In] IntPtr filename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream, [In] int fFullBuild);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __GetDebugInfo([In] ref uint pIDD, [In] uint cData, out uint pcData, [Out] IntPtr data);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineSequencePoints([In, MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] uint spCount, [In] ref uint offsets, [In] ref uint lines, [In] ref uint columns, [In] ref uint endLines, [In] ref uint endColumns);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __RemapToken([In] uint oldToken, [In] uint newToken);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Initialize2([In, MarshalAs(UnmanagedType.IUnknown)] object emitter, [In] IntPtr tempfilename, [In, MarshalAs(UnmanagedType.Interface)] IStream pIStream, [In] int fFullBuild, [In] IntPtr finalfilename);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineConstant([In] IntPtr name, [In, MarshalAs(UnmanagedType.Struct)] object value, [In] uint cSig, [In] ref byte signature);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __Abort();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineLocalVariable2([In] IntPtr name, [In] uint attributes, [In] uint sigToken, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3, [In] uint startOffset, [In] uint endOffset);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineGlobalVariable2([In] IntPtr name, [In] uint attributes, [In] uint sigToken, [In] uint addrKind, [In] uint addr1, [In] uint addr2, [In] uint addr3);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void __DefineConstant2([In] IntPtr name, [In, MarshalAs(UnmanagedType.Struct)] object value, [In] uint sigToken);
}
}
#pragma warning restore 108, 1591

194
Debugger/Debugger.Core/Interop/CorSymExtensionMethods.cs

@ -0,0 +1,194 @@ @@ -0,0 +1,194 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Runtime.InteropServices;
namespace Debugger.Interop.CorSym
{
public static partial class CorSymExtensionMethods
{
static void ProcessOutParameter(object parameter)
{
TrackedComObjects.ProcessOutParameter(parameter);
}
// ISymUnmanagedBinder
public static ISymUnmanagedReader GetReaderForFile(this ISymUnmanagedBinder symBinder, object importer, string filename, string searchPath)
{
IntPtr pfilename = Marshal.StringToCoTaskMemUni(filename);
IntPtr psearchPath = Marshal.StringToCoTaskMemUni(searchPath);
object res = null;
// The method will create the object anyway so we have to use preservesig so that we can release it
// failing to do so would lock the assembly
int code = symBinder.GetReaderForFile(importer, pfilename, psearchPath, ref res);
Marshal.FreeCoTaskMem(pfilename);
Marshal.FreeCoTaskMem(psearchPath);
if (code != 0) {
Marshal.FinalReleaseComObject(res);
throw new COMException("", code);
}
return (ISymUnmanagedReader)res;
}
// ISymUnmanagedDocument
public static string GetURL(this ISymUnmanagedDocument symDoc)
{
return Util.GetCorSymString(symDoc.GetURL);
}
public static unsafe byte[] GetCheckSum(this ISymUnmanagedDocument symDoc)
{
uint actualLength;
byte[] checkSum = new byte[20];
fixed(byte* pCheckSum = checkSum)
symDoc.GetCheckSum((uint)checkSum.Length, out actualLength, new IntPtr(pCheckSum));
if (actualLength > checkSum.Length) {
checkSum = new byte[actualLength];
fixed(byte* pCheckSum = checkSum)
symDoc.GetCheckSum((uint)checkSum.Length, out actualLength, new IntPtr(pCheckSum));
}
if (actualLength == 0) return null;
Array.Resize(ref checkSum, (int)actualLength);
return checkSum;
}
// ISymUnmanagedMethod
public static SequencePoint[] GetSequencePoints(this ISymUnmanagedMethod symMethod)
{
uint count = symMethod.GetSequencePointCount();
ISymUnmanagedDocument[] documents = new ISymUnmanagedDocument[count];
uint[] offsets = new uint[count];
uint[] lines = new uint[count];
uint[] columns = new uint[count];
uint[] endLines = new uint[count];
uint[] endColumns = new uint[count];
symMethod.GetSequencePoints(
count,
out count,
offsets,
documents,
lines,
columns,
endLines,
endColumns
);
SequencePoint[] sequencePoints = new SequencePoint[count];
for(int i = 0; i < count; i++) {
sequencePoints[i] = new SequencePoint() {
Document = documents[i],
Offset = offsets[i],
Line = lines[i],
Column = columns[i],
EndLine = endLines[i],
EndColumn = endColumns[i]
};
}
return sequencePoints;
}
// ISymUnmanagedReader
public static ISymUnmanagedDocument GetDocument(this ISymUnmanagedReader symReader, string url, System.Guid language, System.Guid languageVendor, System.Guid documentType)
{
IntPtr p = Marshal.StringToCoTaskMemUni(url);
ISymUnmanagedDocument res = symReader.GetDocument(p, language, languageVendor, documentType);
Marshal.FreeCoTaskMem(p);
return res;
}
// ISymUnmanagedScope
public static ISymUnmanagedScope[] GetChildren(this ISymUnmanagedScope symScope)
{
uint count;
symScope.GetChildren(0, out count, new ISymUnmanagedScope[0]);
ISymUnmanagedScope[] children = new ISymUnmanagedScope[count];
symScope.GetChildren(count, out count, children);
return children;
}
public static ISymUnmanagedVariable[] GetLocals(this ISymUnmanagedScope symScope)
{
uint count;
symScope.GetLocals(0, out count, new ISymUnmanagedVariable[0]);
ISymUnmanagedVariable[] locals = new ISymUnmanagedVariable[count];
symScope.GetLocals(count, out count, locals);
return locals;
}
public static ISymUnmanagedNamespace[] GetNamespaces(this ISymUnmanagedScope symScope)
{
uint count;
symScope.GetNamespaces(0, out count, new ISymUnmanagedNamespace[0]);
ISymUnmanagedNamespace[] namespaces = new ISymUnmanagedNamespace[count];
symScope.GetNamespaces(count, out count, namespaces);
return namespaces;
}
// ISymUnmanagedNamespace
public static string GetName(this ISymUnmanagedNamespace symNs)
{
return Util.GetCorSymString(symNs.GetName);
}
// ISymUnmanagedVariable
public static string GetName(this ISymUnmanagedVariable symVar)
{
return Util.GetCorSymString(symVar.GetName);
}
const int defaultSigSize = 8;
public static unsafe byte[] GetSignature(this ISymUnmanagedVariable symVar)
{
byte[] sig = new byte[defaultSigSize];
uint acualSize;
fixed(byte* pSig = sig)
symVar.GetSignature((uint)sig.Length, out acualSize, new IntPtr(pSig));
Array.Resize(ref sig, (int)acualSize);
if (acualSize > defaultSigSize)
fixed(byte* pSig = sig)
symVar.GetSignature((uint)sig.Length, out acualSize, new IntPtr(pSig));
return sig;
}
// ISymUnmanagedReader
public static ISymUnmanagedNamespace[] GetNamespaces(this ISymUnmanagedReader symReader)
{
uint count;
symReader.GetNamespaces(0, out count, new ISymUnmanagedNamespace[0]);
ISymUnmanagedNamespace[] namespaces = new ISymUnmanagedNamespace[count];
symReader.GetNamespaces(count, out count, namespaces);
return namespaces;
}
}
public class SequencePoint: IComparable<SequencePoint>
{
public ISymUnmanagedDocument Document { get; internal set; }
public uint Offset { get; internal set; }
public uint Line { get; internal set; }
public uint Column { get; internal set; }
public uint EndLine { get; internal set; }
public uint EndColumn { get; internal set; }
public int CompareTo(SequencePoint other)
{
if (this.Line != other.Line) return this.Line.CompareTo(other.Line);
if (this.Column != other.Column) return this.Column.CompareTo(other.Column);
return this.Offset.CompareTo(other.Offset);
}
}
}

901
Debugger/Debugger.Core/Interop/CorSymExtensionMethods.generated.cs

@ -0,0 +1,901 @@ @@ -0,0 +1,901 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Debugger.Interop.CorSym
{
public static partial class CorSymExtensionMethods
{
public static int GetReaderForFile(this CorSymBinder_SxSClass instance, object importer, IntPtr filename, IntPtr searchPath, ref object retVal)
{
int returnValue = instance.__GetReaderForFile(importer, filename, searchPath, ref retVal);
ProcessOutParameter(retVal);
return returnValue;
}
public static ISymUnmanagedReader GetReaderFromStream(this CorSymBinder_SxSClass instance, object importer, IStream pstream)
{
ISymUnmanagedReader returnValue = instance.__GetReaderFromStream(importer, pstream);
ProcessOutParameter(returnValue);
return returnValue;
}
public static ISymUnmanagedDocument GetDocument(this CorSymReader_SxSClass instance, IntPtr url, Guid language, Guid languageVendor, Guid documentType)
{
ISymUnmanagedDocument returnValue = instance.__GetDocument(url, language, languageVendor, documentType);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void GetDocuments(this CorSymReader_SxSClass instance, uint cDocs, out uint pcDocs, ISymUnmanagedDocument[] pDocs)
{
instance.__GetDocuments(cDocs, out pcDocs, pDocs);
ProcessOutParameter(pDocs);
}
public static void GetDocumentVersion(this CorSymReader_SxSClass instance, ISymUnmanagedDocument pDoc, out int version, out int pbCurrent)
{
instance.__GetDocumentVersion(pDoc, out version, out pbCurrent);
}
public static void GetGlobalVariables(this CorSymReader_SxSClass instance, uint cVars, out uint pcVars, IntPtr pVars)
{
instance.__GetGlobalVariables(cVars, out pcVars, pVars);
}
public static ISymUnmanagedMethod GetMethod(this CorSymReader_SxSClass instance, uint token)
{
ISymUnmanagedMethod returnValue = instance.__GetMethod(token);
ProcessOutParameter(returnValue);
return returnValue;
}
public static ISymUnmanagedMethod GetMethodByVersion(this CorSymReader_SxSClass instance, uint token, int version)
{
ISymUnmanagedMethod returnValue = instance.__GetMethodByVersion(token, version);
ProcessOutParameter(returnValue);
return returnValue;
}
public static ISymUnmanagedMethod GetMethodFromDocumentPosition(this CorSymReader_SxSClass instance, ISymUnmanagedDocument document, uint line, uint column)
{
ISymUnmanagedMethod returnValue = instance.__GetMethodFromDocumentPosition(document, line, column);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void GetMethodsFromDocumentPosition(this CorSymReader_SxSClass instance, ISymUnmanagedDocument document, uint line, uint column, uint cMethod, out uint pcMethod, IntPtr pRetVal)
{
instance.__GetMethodsFromDocumentPosition(document, line, column, cMethod, out pcMethod, pRetVal);
}
public static int GetMethodVersion(this CorSymReader_SxSClass instance, ISymUnmanagedMethod pMethod)
{
int version;
instance.__GetMethodVersion(pMethod, out version);
return version;
}
public static void GetNamespaces(this CorSymReader_SxSClass instance, uint cNameSpaces, out uint pcNameSpaces, ISymUnmanagedNamespace[] namespaces)
{
instance.__GetNamespaces(cNameSpaces, out pcNameSpaces, namespaces);
ProcessOutParameter(namespaces);
}
public static void GetSymAttribute(this CorSymReader_SxSClass instance, uint parent, IntPtr name, uint cBuffer, out uint pcBuffer, IntPtr buffer)
{
instance.__GetSymAttribute(parent, name, cBuffer, out pcBuffer, buffer);
}
public static void GetSymbolStoreFileName(this CorSymReader_SxSClass instance, uint cchName, out uint pcchName, IntPtr szName)
{
instance.__GetSymbolStoreFileName(cchName, out pcchName, szName);
}
public static uint GetUserEntryPoint(this CorSymReader_SxSClass instance)
{
return instance.__GetUserEntryPoint();
}
public static void GetVariables(this CorSymReader_SxSClass instance, uint parent, uint cVars, out uint pcVars, IntPtr pVars)
{
instance.__GetVariables(parent, cVars, out pcVars, pVars);
}
public static void Initialize(this CorSymReader_SxSClass instance, object importer, IntPtr filename, IntPtr searchPath, IStream pIStream)
{
instance.__Initialize(importer, filename, searchPath, pIStream);
}
public static void ReplaceSymbolStore(this CorSymReader_SxSClass instance, IntPtr filename, IStream pIStream)
{
instance.__ReplaceSymbolStore(filename, pIStream);
}
public static void UpdateSymbolStore(this CorSymReader_SxSClass instance, IntPtr filename, IStream pIStream)
{
instance.__UpdateSymbolStore(filename, pIStream);
}
public static void Abort(this CorSymWriter_SxSClass instance)
{
instance.__Abort();
}
public static void Close(this CorSymWriter_SxSClass instance)
{
instance.__Close();
}
public static void CloseMethod(this CorSymWriter_SxSClass instance)
{
instance.__CloseMethod();
}
public static void CloseNamespace(this CorSymWriter_SxSClass instance)
{
instance.__CloseNamespace();
}
public static void CloseScope(this CorSymWriter_SxSClass instance, uint endOffset)
{
instance.__CloseScope(endOffset);
}
public static void DefineConstant(this CorSymWriter_SxSClass instance, IntPtr name, object value, uint cSig, ref byte signature)
{
instance.__DefineConstant(name, value, cSig, ref signature);
ProcessOutParameter(signature);
}
public static ISymUnmanagedDocumentWriter DefineDocument(this CorSymWriter_SxSClass instance, IntPtr url, ref Guid language, ref Guid languageVendor, ref Guid documentType)
{
ISymUnmanagedDocumentWriter returnValue = instance.__DefineDocument(url, ref language, ref languageVendor, ref documentType);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void DefineField(this CorSymWriter_SxSClass instance, uint parent, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineField(parent, name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3);
ProcessOutParameter(signature);
}
public static void DefineGlobalVariable(this CorSymWriter_SxSClass instance, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineGlobalVariable(name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3);
ProcessOutParameter(signature);
}
public static void DefineLocalVariable(this CorSymWriter_SxSClass instance, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3, uint startOffset,
uint endOffset)
{
instance.__DefineLocalVariable(name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3, startOffset, endOffset);
ProcessOutParameter(signature);
}
public static void DefineParameter(this CorSymWriter_SxSClass instance, IntPtr name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineParameter(name, attributes, sequence, addrKind, addr1, addr2, addr3);
}
public static void DefineSequencePoints(this CorSymWriter_SxSClass instance, ISymUnmanagedDocumentWriter document, uint spCount, ref uint offsets, ref uint lines, ref uint columns, ref uint endLines, ref uint endColumns)
{
instance.__DefineSequencePoints(document, spCount, ref offsets, ref lines, ref columns, ref endLines, ref endColumns);
}
public static void GetDebugInfo(this CorSymWriter_SxSClass instance, ref uint pIDD, uint cData, out uint pcData, IntPtr data)
{
instance.__GetDebugInfo(ref pIDD, cData, out pcData, data);
}
public static void Initialize(this CorSymWriter_SxSClass instance, object emitter, IntPtr filename, IStream pIStream, int fFullBuild)
{
instance.__Initialize(emitter, filename, pIStream, fFullBuild);
}
public static void Initialize2(this CorSymWriter_SxSClass instance, object emitter, IntPtr tempfilename, IStream pIStream, int fFullBuild, IntPtr finalfilename)
{
instance.__Initialize2(emitter, tempfilename, pIStream, fFullBuild, finalfilename);
}
public static void OpenMethod(this CorSymWriter_SxSClass instance, uint method)
{
instance.__OpenMethod(method);
}
public static void OpenNamespace(this CorSymWriter_SxSClass instance, IntPtr name)
{
instance.__OpenNamespace(name);
}
public static uint OpenScope(this CorSymWriter_SxSClass instance, uint startOffset)
{
return instance.__OpenScope(startOffset);
}
public static void RemapToken(this CorSymWriter_SxSClass instance, uint oldToken, uint newToken)
{
instance.__RemapToken(oldToken, newToken);
}
public static void SetMethodSourceRange(this CorSymWriter_SxSClass instance, ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, ISymUnmanagedDocumentWriter endDoc, uint endLine, uint endColumn)
{
instance.__SetMethodSourceRange(startDoc, startLine, startColumn, endDoc, endLine, endColumn);
}
public static void SetScopeRange(this CorSymWriter_SxSClass instance, uint scopeID, uint startOffset, uint endOffset)
{
instance.__SetScopeRange(scopeID, startOffset, endOffset);
}
public static void SetSymAttribute(this CorSymWriter_SxSClass instance, uint parent, IntPtr name, uint cData, ref byte data)
{
instance.__SetSymAttribute(parent, name, cData, ref data);
ProcessOutParameter(data);
}
public static void SetUserEntryPoint(this CorSymWriter_SxSClass instance, uint entryMethod)
{
instance.__SetUserEntryPoint(entryMethod);
}
public static void UsingNamespace(this CorSymWriter_SxSClass instance, IntPtr fullName)
{
instance.__UsingNamespace(fullName);
}
public static int GetReaderForFile(this ISymUnmanagedBinder instance, object importer, IntPtr filename, IntPtr searchPath, ref object retVal)
{
int returnValue = instance.__GetReaderForFile(importer, filename, searchPath, ref retVal);
ProcessOutParameter(retVal);
return returnValue;
}
public static ISymUnmanagedReader GetReaderFromStream(this ISymUnmanagedBinder instance, object importer, IStream pstream)
{
ISymUnmanagedReader returnValue = instance.__GetReaderFromStream(importer, pstream);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void Destroy(this ISymUnmanagedDispose instance)
{
instance.__Destroy();
}
public static void GetURL(this ISymUnmanagedDocument instance, uint cchUrl, out uint pcchUrl, IntPtr szUrl)
{
instance.__GetURL(cchUrl, out pcchUrl, szUrl);
}
public static Guid GetDocumentType(this ISymUnmanagedDocument instance)
{
return instance.__GetDocumentType();
}
public static Guid GetLanguage(this ISymUnmanagedDocument instance)
{
return instance.__GetLanguage();
}
public static Guid GetLanguageVendor(this ISymUnmanagedDocument instance)
{
return instance.__GetLanguageVendor();
}
public static Guid GetCheckSumAlgorithmId(this ISymUnmanagedDocument instance)
{
return instance.__GetCheckSumAlgorithmId();
}
public static void GetCheckSum(this ISymUnmanagedDocument instance, uint cData, out uint pcData, IntPtr data)
{
instance.__GetCheckSum(cData, out pcData, data);
}
public static uint FindClosestLine(this ISymUnmanagedDocument instance, uint line)
{
return instance.__FindClosestLine(line);
}
public static int HasEmbeddedSource(this ISymUnmanagedDocument instance)
{
return instance.__HasEmbeddedSource();
}
public static uint GetSourceLength(this ISymUnmanagedDocument instance)
{
return instance.__GetSourceLength();
}
public static void GetSourceRange(this ISymUnmanagedDocument instance, uint startLine, uint startColumn, uint endLine, uint endColumn, uint cSourceBytes, out uint pcSourceBytes, IntPtr source)
{
instance.__GetSourceRange(startLine, startColumn, endLine, endColumn, cSourceBytes, out pcSourceBytes, source);
}
public static void SetSource(this ISymUnmanagedDocumentWriter instance, uint sourceSize, ref byte source)
{
instance.__SetSource(sourceSize, ref source);
ProcessOutParameter(source);
}
public static void SetCheckSum(this ISymUnmanagedDocumentWriter instance, Guid algorithmId, uint checkSumSize, ref byte checkSum)
{
instance.__SetCheckSum(algorithmId, checkSumSize, ref checkSum);
ProcessOutParameter(checkSum);
}
public static uint GetToken(this ISymUnmanagedMethod instance)
{
return instance.__GetToken();
}
public static uint GetSequencePointCount(this ISymUnmanagedMethod instance)
{
return instance.__GetSequencePointCount();
}
public static ISymUnmanagedScope GetRootScope(this ISymUnmanagedMethod instance)
{
ISymUnmanagedScope returnValue = instance.__GetRootScope();
ProcessOutParameter(returnValue);
return returnValue;
}
public static ISymUnmanagedScope GetScopeFromOffset(this ISymUnmanagedMethod instance, uint offset)
{
ISymUnmanagedScope returnValue = instance.__GetScopeFromOffset(offset);
ProcessOutParameter(returnValue);
return returnValue;
}
public static uint GetOffset(this ISymUnmanagedMethod instance, ISymUnmanagedDocument document, uint line, uint column)
{
return instance.__GetOffset(document, line, column);
}
public static void GetRanges(this ISymUnmanagedMethod instance, ISymUnmanagedDocument document, uint line, uint column, uint cRanges, out uint pcRanges, IntPtr ranges)
{
instance.__GetRanges(document, line, column, cRanges, out pcRanges, ranges);
}
public static void GetParameters(this ISymUnmanagedMethod instance, uint cParams, out uint pcParams, IntPtr @params)
{
instance.__GetParameters(cParams, out pcParams, @params);
}
public static ISymUnmanagedNamespace GetNamespace(this ISymUnmanagedMethod instance)
{
ISymUnmanagedNamespace pRetVal;
instance.__GetNamespace(out pRetVal);
ProcessOutParameter(pRetVal);
return pRetVal;
}
public static int GetSourceStartEnd(this ISymUnmanagedMethod instance, ISymUnmanagedDocument[] docs, uint[] lines, uint[] columns)
{
int pRetVal;
instance.__GetSourceStartEnd(docs, lines, columns, out pRetVal);
ProcessOutParameter(docs);
return pRetVal;
}
public static void GetSequencePoints(this ISymUnmanagedMethod instance, uint cPoints, out uint pcPoints, uint[] offsets, ISymUnmanagedDocument[] documents, uint[] lines, uint[] columns, uint[] endLines, uint[] endColumns)
{
instance.__GetSequencePoints(cPoints, out pcPoints, offsets, documents, lines, columns, endLines, endColumns);
ProcessOutParameter(documents);
}
public static void GetName(this ISymUnmanagedNamespace instance, uint cchName, out uint pcchName, IntPtr szName)
{
instance.__GetName(cchName, out pcchName, szName);
}
public static void GetNamespaces(this ISymUnmanagedNamespace instance, uint cNameSpaces, out uint pcNameSpaces, IntPtr namespaces)
{
instance.__GetNamespaces(cNameSpaces, out pcNameSpaces, namespaces);
}
public static void GetVariables(this ISymUnmanagedNamespace instance, uint cVars, out uint pcVars, IntPtr pVars)
{
instance.__GetVariables(cVars, out pcVars, pVars);
}
public static ISymUnmanagedDocument GetDocument(this ISymUnmanagedReader instance, IntPtr url, Guid language, Guid languageVendor, Guid documentType)
{
ISymUnmanagedDocument returnValue = instance.__GetDocument(url, language, languageVendor, documentType);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void GetDocuments(this ISymUnmanagedReader instance, uint cDocs, out uint pcDocs, ISymUnmanagedDocument[] pDocs)
{
instance.__GetDocuments(cDocs, out pcDocs, pDocs);
ProcessOutParameter(pDocs);
}
public static uint GetUserEntryPoint(this ISymUnmanagedReader instance)
{
return instance.__GetUserEntryPoint();
}
public static ISymUnmanagedMethod GetMethod(this ISymUnmanagedReader instance, uint token)
{
ISymUnmanagedMethod returnValue = instance.__GetMethod(token);
ProcessOutParameter(returnValue);
return returnValue;
}
public static ISymUnmanagedMethod GetMethodByVersion(this ISymUnmanagedReader instance, uint token, int version)
{
ISymUnmanagedMethod returnValue = instance.__GetMethodByVersion(token, version);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void GetVariables(this ISymUnmanagedReader instance, uint parent, uint cVars, out uint pcVars, IntPtr pVars)
{
instance.__GetVariables(parent, cVars, out pcVars, pVars);
}
public static void GetGlobalVariables(this ISymUnmanagedReader instance, uint cVars, out uint pcVars, IntPtr pVars)
{
instance.__GetGlobalVariables(cVars, out pcVars, pVars);
}
public static ISymUnmanagedMethod GetMethodFromDocumentPosition(this ISymUnmanagedReader instance, ISymUnmanagedDocument document, uint line, uint column)
{
ISymUnmanagedMethod returnValue = instance.__GetMethodFromDocumentPosition(document, line, column);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void GetSymAttribute(this ISymUnmanagedReader instance, uint parent, IntPtr name, uint cBuffer, out uint pcBuffer, IntPtr buffer)
{
instance.__GetSymAttribute(parent, name, cBuffer, out pcBuffer, buffer);
}
public static void GetNamespaces(this ISymUnmanagedReader instance, uint cNameSpaces, out uint pcNameSpaces, ISymUnmanagedNamespace[] namespaces)
{
instance.__GetNamespaces(cNameSpaces, out pcNameSpaces, namespaces);
ProcessOutParameter(namespaces);
}
public static void Initialize(this ISymUnmanagedReader instance, object importer, IntPtr filename, IntPtr searchPath, IStream pIStream)
{
instance.__Initialize(importer, filename, searchPath, pIStream);
}
public static void UpdateSymbolStore(this ISymUnmanagedReader instance, IntPtr filename, IStream pIStream)
{
instance.__UpdateSymbolStore(filename, pIStream);
}
public static void ReplaceSymbolStore(this ISymUnmanagedReader instance, IntPtr filename, IStream pIStream)
{
instance.__ReplaceSymbolStore(filename, pIStream);
}
public static void GetSymbolStoreFileName(this ISymUnmanagedReader instance, uint cchName, out uint pcchName, IntPtr szName)
{
instance.__GetSymbolStoreFileName(cchName, out pcchName, szName);
}
public static void GetMethodsFromDocumentPosition(this ISymUnmanagedReader instance, ISymUnmanagedDocument document, uint line, uint column, uint cMethod, out uint pcMethod, IntPtr pRetVal)
{
instance.__GetMethodsFromDocumentPosition(document, line, column, cMethod, out pcMethod, pRetVal);
}
public static void GetDocumentVersion(this ISymUnmanagedReader instance, ISymUnmanagedDocument pDoc, out int version, out int pbCurrent)
{
instance.__GetDocumentVersion(pDoc, out version, out pbCurrent);
}
public static int GetMethodVersion(this ISymUnmanagedReader instance, ISymUnmanagedMethod pMethod)
{
int version;
instance.__GetMethodVersion(pMethod, out version);
return version;
}
public static uint GetSymbolSearchInfoCount(this ISymUnmanagedReaderSymbolSearchInfo instance)
{
uint pcSearchInfo;
instance.__GetSymbolSearchInfoCount(out pcSearchInfo);
return pcSearchInfo;
}
public static void GetSymbolSearchInfo(this ISymUnmanagedReaderSymbolSearchInfo instance, uint cSearchInfo, out uint pcSearchInfo, out ISymUnmanagedSymbolSearchInfo rgpSearchInfo)
{
instance.__GetSymbolSearchInfo(cSearchInfo, out pcSearchInfo, out rgpSearchInfo);
ProcessOutParameter(rgpSearchInfo);
}
public static ISymUnmanagedMethod GetMethod(this ISymUnmanagedScope instance)
{
ISymUnmanagedMethod returnValue = instance.__GetMethod();
ProcessOutParameter(returnValue);
return returnValue;
}
public static ISymUnmanagedScope GetParent(this ISymUnmanagedScope instance)
{
ISymUnmanagedScope returnValue = instance.__GetParent();
ProcessOutParameter(returnValue);
return returnValue;
}
public static void GetChildren(this ISymUnmanagedScope instance, uint cChildren, out uint pcChildren, ISymUnmanagedScope[] children)
{
instance.__GetChildren(cChildren, out pcChildren, children);
ProcessOutParameter(children);
}
public static uint GetStartOffset(this ISymUnmanagedScope instance)
{
return instance.__GetStartOffset();
}
public static uint GetEndOffset(this ISymUnmanagedScope instance)
{
return instance.__GetEndOffset();
}
public static uint GetLocalCount(this ISymUnmanagedScope instance)
{
return instance.__GetLocalCount();
}
public static void GetLocals(this ISymUnmanagedScope instance, uint cLocals, out uint pcLocals, ISymUnmanagedVariable[] locals)
{
instance.__GetLocals(cLocals, out pcLocals, locals);
ProcessOutParameter(locals);
}
public static void GetNamespaces(this ISymUnmanagedScope instance, uint cNameSpaces, out uint pcNameSpaces, ISymUnmanagedNamespace[] namespaces)
{
instance.__GetNamespaces(cNameSpaces, out pcNameSpaces, namespaces);
ProcessOutParameter(namespaces);
}
public static uint GetSearchPathLength(this ISymUnmanagedSymbolSearchInfo instance)
{
uint pcchPath;
instance.__GetSearchPathLength(out pcchPath);
return pcchPath;
}
public static void GetSearchPath(this ISymUnmanagedSymbolSearchInfo instance, uint cchPath, out uint pcchPath, IntPtr szPath)
{
instance.__GetSearchPath(cchPath, out pcchPath, szPath);
}
public static int GetHRESULT(this ISymUnmanagedSymbolSearchInfo instance)
{
int phr;
instance.__GetHRESULT(out phr);
return phr;
}
public static void GetName(this ISymUnmanagedVariable instance, uint cchName, out uint pcchName, IntPtr szName)
{
instance.__GetName(cchName, out pcchName, szName);
}
public static uint GetAttributes(this ISymUnmanagedVariable instance)
{
return instance.__GetAttributes();
}
public static void GetSignature(this ISymUnmanagedVariable instance, uint cSig, out uint pcSig, IntPtr sig)
{
instance.__GetSignature(cSig, out pcSig, sig);
}
public static uint GetAddressKind(this ISymUnmanagedVariable instance)
{
return instance.__GetAddressKind();
}
public static uint GetAddressField1(this ISymUnmanagedVariable instance)
{
return instance.__GetAddressField1();
}
public static uint GetAddressField2(this ISymUnmanagedVariable instance)
{
return instance.__GetAddressField2();
}
public static uint GetAddressField3(this ISymUnmanagedVariable instance)
{
return instance.__GetAddressField3();
}
public static uint GetStartOffset(this ISymUnmanagedVariable instance)
{
return instance.__GetStartOffset();
}
public static uint GetEndOffset(this ISymUnmanagedVariable instance)
{
return instance.__GetEndOffset();
}
public static ISymUnmanagedDocumentWriter DefineDocument(this ISymUnmanagedWriter instance, IntPtr url, ref Guid language, ref Guid languageVendor, ref Guid documentType)
{
ISymUnmanagedDocumentWriter returnValue = instance.__DefineDocument(url, ref language, ref languageVendor, ref documentType);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void SetUserEntryPoint(this ISymUnmanagedWriter instance, uint entryMethod)
{
instance.__SetUserEntryPoint(entryMethod);
}
public static void OpenMethod(this ISymUnmanagedWriter instance, uint method)
{
instance.__OpenMethod(method);
}
public static void CloseMethod(this ISymUnmanagedWriter instance)
{
instance.__CloseMethod();
}
public static uint OpenScope(this ISymUnmanagedWriter instance, uint startOffset)
{
return instance.__OpenScope(startOffset);
}
public static void CloseScope(this ISymUnmanagedWriter instance, uint endOffset)
{
instance.__CloseScope(endOffset);
}
public static void SetScopeRange(this ISymUnmanagedWriter instance, uint scopeID, uint startOffset, uint endOffset)
{
instance.__SetScopeRange(scopeID, startOffset, endOffset);
}
public static void DefineLocalVariable(this ISymUnmanagedWriter instance, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3, uint startOffset,
uint endOffset)
{
instance.__DefineLocalVariable(name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3, startOffset, endOffset);
ProcessOutParameter(signature);
}
public static void DefineParameter(this ISymUnmanagedWriter instance, IntPtr name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineParameter(name, attributes, sequence, addrKind, addr1, addr2, addr3);
}
public static void DefineField(this ISymUnmanagedWriter instance, uint parent, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineField(parent, name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3);
ProcessOutParameter(signature);
}
public static void DefineGlobalVariable(this ISymUnmanagedWriter instance, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineGlobalVariable(name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3);
ProcessOutParameter(signature);
}
public static void Close(this ISymUnmanagedWriter instance)
{
instance.__Close();
}
public static void SetSymAttribute(this ISymUnmanagedWriter instance, uint parent, IntPtr name, uint cData, ref byte data)
{
instance.__SetSymAttribute(parent, name, cData, ref data);
ProcessOutParameter(data);
}
public static void OpenNamespace(this ISymUnmanagedWriter instance, IntPtr name)
{
instance.__OpenNamespace(name);
}
public static void CloseNamespace(this ISymUnmanagedWriter instance)
{
instance.__CloseNamespace();
}
public static void UsingNamespace(this ISymUnmanagedWriter instance, IntPtr fullName)
{
instance.__UsingNamespace(fullName);
}
public static void SetMethodSourceRange(this ISymUnmanagedWriter instance, ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, ISymUnmanagedDocumentWriter endDoc, uint endLine, uint endColumn)
{
instance.__SetMethodSourceRange(startDoc, startLine, startColumn, endDoc, endLine, endColumn);
}
public static void Initialize(this ISymUnmanagedWriter instance, object emitter, IntPtr filename, IStream pIStream, int fFullBuild)
{
instance.__Initialize(emitter, filename, pIStream, fFullBuild);
}
public static void GetDebugInfo(this ISymUnmanagedWriter instance, ref uint pIDD, uint cData, out uint pcData, IntPtr data)
{
instance.__GetDebugInfo(ref pIDD, cData, out pcData, data);
}
public static void DefineSequencePoints(this ISymUnmanagedWriter instance, ISymUnmanagedDocumentWriter document, uint spCount, ref uint offsets, ref uint lines, ref uint columns, ref uint endLines, ref uint endColumns)
{
instance.__DefineSequencePoints(document, spCount, ref offsets, ref lines, ref columns, ref endLines, ref endColumns);
}
public static void RemapToken(this ISymUnmanagedWriter instance, uint oldToken, uint newToken)
{
instance.__RemapToken(oldToken, newToken);
}
public static void Initialize2(this ISymUnmanagedWriter instance, object emitter, IntPtr tempfilename, IStream pIStream, int fFullBuild, IntPtr finalfilename)
{
instance.__Initialize2(emitter, tempfilename, pIStream, fFullBuild, finalfilename);
}
public static void DefineConstant(this ISymUnmanagedWriter instance, IntPtr name, object value, uint cSig, ref byte signature)
{
instance.__DefineConstant(name, value, cSig, ref signature);
ProcessOutParameter(signature);
}
public static void Abort(this ISymUnmanagedWriter instance)
{
instance.__Abort();
}
public static ISymUnmanagedDocumentWriter DefineDocument(this ISymUnmanagedWriter2 instance, IntPtr url, ref Guid language, ref Guid languageVendor, ref Guid documentType)
{
ISymUnmanagedDocumentWriter returnValue = instance.__DefineDocument(url, ref language, ref languageVendor, ref documentType);
ProcessOutParameter(returnValue);
return returnValue;
}
public static void SetUserEntryPoint(this ISymUnmanagedWriter2 instance, uint entryMethod)
{
instance.__SetUserEntryPoint(entryMethod);
}
public static void OpenMethod(this ISymUnmanagedWriter2 instance, uint method)
{
instance.__OpenMethod(method);
}
public static void CloseMethod(this ISymUnmanagedWriter2 instance)
{
instance.__CloseMethod();
}
public static uint OpenScope(this ISymUnmanagedWriter2 instance, uint startOffset)
{
return instance.__OpenScope(startOffset);
}
public static void CloseScope(this ISymUnmanagedWriter2 instance, uint endOffset)
{
instance.__CloseScope(endOffset);
}
public static void SetScopeRange(this ISymUnmanagedWriter2 instance, uint scopeID, uint startOffset, uint endOffset)
{
instance.__SetScopeRange(scopeID, startOffset, endOffset);
}
public static void DefineLocalVariable(this ISymUnmanagedWriter2 instance, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3, uint startOffset,
uint endOffset)
{
instance.__DefineLocalVariable(name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3, startOffset, endOffset);
ProcessOutParameter(signature);
}
public static void DefineParameter(this ISymUnmanagedWriter2 instance, IntPtr name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineParameter(name, attributes, sequence, addrKind, addr1, addr2, addr3);
}
public static void DefineField(this ISymUnmanagedWriter2 instance, uint parent, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineField(parent, name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3);
ProcessOutParameter(signature);
}
public static void DefineGlobalVariable(this ISymUnmanagedWriter2 instance, IntPtr name, uint attributes, uint cSig, ref byte signature, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineGlobalVariable(name, attributes, cSig, ref signature, addrKind, addr1, addr2, addr3);
ProcessOutParameter(signature);
}
public static void Close(this ISymUnmanagedWriter2 instance)
{
instance.__Close();
}
public static void SetSymAttribute(this ISymUnmanagedWriter2 instance, uint parent, IntPtr name, uint cData, ref byte data)
{
instance.__SetSymAttribute(parent, name, cData, ref data);
ProcessOutParameter(data);
}
public static void OpenNamespace(this ISymUnmanagedWriter2 instance, IntPtr name)
{
instance.__OpenNamespace(name);
}
public static void CloseNamespace(this ISymUnmanagedWriter2 instance)
{
instance.__CloseNamespace();
}
public static void UsingNamespace(this ISymUnmanagedWriter2 instance, IntPtr fullName)
{
instance.__UsingNamespace(fullName);
}
public static void SetMethodSourceRange(this ISymUnmanagedWriter2 instance, ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, ISymUnmanagedDocumentWriter endDoc, uint endLine, uint endColumn)
{
instance.__SetMethodSourceRange(startDoc, startLine, startColumn, endDoc, endLine, endColumn);
}
public static void Initialize(this ISymUnmanagedWriter2 instance, object emitter, IntPtr filename, IStream pIStream, int fFullBuild)
{
instance.__Initialize(emitter, filename, pIStream, fFullBuild);
}
public static void GetDebugInfo(this ISymUnmanagedWriter2 instance, ref uint pIDD, uint cData, out uint pcData, IntPtr data)
{
instance.__GetDebugInfo(ref pIDD, cData, out pcData, data);
}
public static void DefineSequencePoints(this ISymUnmanagedWriter2 instance, ISymUnmanagedDocumentWriter document, uint spCount, ref uint offsets, ref uint lines, ref uint columns, ref uint endLines, ref uint endColumns)
{
instance.__DefineSequencePoints(document, spCount, ref offsets, ref lines, ref columns, ref endLines, ref endColumns);
}
public static void RemapToken(this ISymUnmanagedWriter2 instance, uint oldToken, uint newToken)
{
instance.__RemapToken(oldToken, newToken);
}
public static void Initialize2(this ISymUnmanagedWriter2 instance, object emitter, IntPtr tempfilename, IStream pIStream, int fFullBuild, IntPtr finalfilename)
{
instance.__Initialize2(emitter, tempfilename, pIStream, fFullBuild, finalfilename);
}
public static void DefineConstant(this ISymUnmanagedWriter2 instance, IntPtr name, object value, uint cSig, ref byte signature)
{
instance.__DefineConstant(name, value, cSig, ref signature);
ProcessOutParameter(signature);
}
public static void Abort(this ISymUnmanagedWriter2 instance)
{
instance.__Abort();
}
public static void DefineLocalVariable2(this ISymUnmanagedWriter2 instance, IntPtr name, uint attributes, uint sigToken, uint addrKind, uint addr1, uint addr2, uint addr3, uint startOffset, uint endOffset)
{
instance.__DefineLocalVariable2(name, attributes, sigToken, addrKind, addr1, addr2, addr3, startOffset, endOffset);
}
public static void DefineGlobalVariable2(this ISymUnmanagedWriter2 instance, IntPtr name, uint attributes, uint sigToken, uint addrKind, uint addr1, uint addr2, uint addr3)
{
instance.__DefineGlobalVariable2(name, attributes, sigToken, addrKind, addr1, addr2, addr3);
}
public static void DefineConstant2(this ISymUnmanagedWriter2 instance, IntPtr name, object value, uint sigToken)
{
instance.__DefineConstant2(name, value, sigToken);
}
}
}

252
Debugger/Debugger.Core/Interop/MTA2STA.cs

@ -0,0 +1,252 @@ @@ -0,0 +1,252 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace Debugger
{
public delegate T MethodInvokerWithReturnValue<T>();
public enum CallMethod {DirectCall, Manual, HiddenForm, HiddenFormWithTimeout};
public class MTA2STA
{
Form hiddenForm;
IntPtr hiddenFormHandle;
System.Threading.Thread targetThread;
CallMethod callMethod = CallMethod.HiddenFormWithTimeout;
Queue<MethodInvoker> pendingCalls = new Queue<MethodInvoker>();
ManualResetEvent pendingCallsNotEmpty = new ManualResetEvent(false);
WaitHandle EnqueueCall(MethodInvoker callDelegate)
{
lock (pendingCalls) {
ManualResetEvent callDone = new ManualResetEvent(false);
pendingCalls.Enqueue(delegate{
callDelegate();
callDone.Set();
});
pendingCallsNotEmpty.Set();
return callDone;
}
}
/// <summary>
/// Wait until a call a made
/// </summary>
public void WaitForCall()
{
pendingCallsNotEmpty.WaitOne();
}
public void WaitForCall(TimeSpan timeout)
{
pendingCallsNotEmpty.WaitOne(timeout, false);
}
/// <summary>
/// Performs all waiting calls on the current thread
/// </summary>
public void PerformAllCalls()
{
while (true) {
if (!PerformCall()) {
return;
}
}
}
/// <summary>
/// Performs all waiting calls on the current thread
/// </summary>
/// <remarks>
/// Private - user should always drain the queue - otherwise Prcoess.RaisePausedEvents might fail
/// </remarks>
bool PerformCall()
{
MethodInvoker nextMethod;
lock (pendingCalls) {
if (pendingCalls.Count > 0) {
nextMethod = pendingCalls.Dequeue();
} else {
pendingCallsNotEmpty.Reset();
return false;
}
}
nextMethod();
return true;
}
public CallMethod CallMethod {
get {
return callMethod;
}
set {
callMethod = value;
}
}
public MTA2STA()
{
targetThread = System.Threading.Thread.CurrentThread;
hiddenForm = new Form();
// Force handle creation
hiddenFormHandle = hiddenForm.Handle;
}
/// <summary>
/// SoftWait waits for any of the given WaitHandles and allows processing of calls during the wait
/// </summary>
public int SoftWait(params WaitHandle[] waitFor)
{
List<WaitHandle> waits = new List<WaitHandle> (waitFor);
waits.Add(pendingCallsNotEmpty);
while(true) {
int i = WaitHandle.WaitAny(waits.ToArray());
PerformAllCalls();
if (i < waits.Count - 1) { // If not pendingCallsNotEmpty
return i;
}
}
}
/// <summary>
/// Schedules invocation of method and returns immediately
/// </summary>
public WaitHandle AsyncCall(MethodInvoker callDelegate)
{
WaitHandle callDone = EnqueueCall(callDelegate);
TriggerInvoke();
return callDone;
}
public T Call<T>(MethodInvokerWithReturnValue<T> callDelegate)
{
T returnValue = default(T);
Call(delegate { returnValue = callDelegate(); }, true);
return returnValue;
}
public void Call(MethodInvoker callDelegate)
{
Call(callDelegate, false);
}
void Call(MethodInvoker callDelegate, bool hasReturnValue)
{
// Enqueue the call
WaitHandle callDone = EnqueueCall(callDelegate);
if (targetThread == System.Threading.Thread.CurrentThread) {
PerformAllCalls();
return;
}
// We have the call waiting in queue, we need to call it (not waiting for it to finish)
TriggerInvoke();
// Wait for the call to finish
if (!hasReturnValue && callMethod == CallMethod.HiddenFormWithTimeout) {
// Give it 5 seconds to run
if (!callDone.WaitOne(5000, true)) {
System.Console.WriteLine("Call time out! (continuing)");
System.Console.WriteLine(new System.Diagnostics.StackTrace(true).ToString());
}
} else {
callDone.WaitOne();
}
}
void TriggerInvoke()
{
switch (callMethod) {
case CallMethod.DirectCall:
PerformAllCalls();
break;
case CallMethod.Manual:
// Nothing we can do - someone else must call SoftWait or Pulse
break;
case CallMethod.HiddenForm:
case CallMethod.HiddenFormWithTimeout:
hiddenForm.BeginInvoke((MethodInvoker)PerformAllCalls);
break;
}
}
public static object MarshalParamTo(object param, Type outputType)
{
if (param is IntPtr) {
return MarshalIntPtrTo((IntPtr)param, outputType);
} else {
return param;
}
}
public static T MarshalIntPtrTo<T>(IntPtr param)
{
return (T)MarshalIntPtrTo(param, typeof(T));
}
public static object MarshalIntPtrTo(IntPtr param, Type outputType)
{
// IntPtr requested as output (must be before the null check so that we pass IntPtr.Zero)
if (outputType == typeof(IntPtr)) {
return param;
}
// The parameter is null pointer
if ((IntPtr)param == IntPtr.Zero) {
return null;
}
// String requested as output
if (outputType == typeof(string)) {
return Marshal.PtrToStringAuto((IntPtr)param);
}
// Marshal a COM object
object comObject = Marshal.GetObjectForIUnknown(param);
Debugger.Interop.TrackedComObjects.Track(comObject);
return comObject;
}
/// <summary>
/// Uses reflection to call method. Automaticaly marshals parameters.
/// </summary>
/// <param name="targetObject">Targed object which contains the method. In case of static mehod pass the Type</param>
/// <param name="functionName">The name of the function to call</param>
/// <param name="functionParameters">Parameters which should be send to the function. Parameters will be marshaled to proper type.</param>
/// <returns>Return value of the called function</returns>
public static object InvokeMethod(object targetObject, string functionName, object[] functionParameters)
{
System.Reflection.MethodInfo method;
if (targetObject is Type) {
method = ((Type)targetObject).GetMethod(functionName);
} else {
method = targetObject.GetType().GetMethod(functionName);
}
ParameterInfo[] methodParamsInfo = method.GetParameters();
object[] convertedParams = new object[methodParamsInfo.Length];
for (int i = 0; i < convertedParams.Length; i++) {
convertedParams[i] = MarshalParamTo(functionParameters[i], methodParamsInfo[i].ParameterType);
}
try {
if (targetObject is Type) {
return method.Invoke(null, convertedParams);
} else {
return method.Invoke(targetObject, convertedParams);
}
} catch (System.Exception exception) {
throw new Debugger.DebuggerException("Invoke of " + functionName + " failed.", exception);
}
}
}
}

278
Debugger/Debugger.Core/Interop/MetaData.cs

@ -0,0 +1,278 @@ @@ -0,0 +1,278 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
#pragma warning disable 108, 1591
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Debugger.Interop.MetaData
{
[StructLayout(LayoutKind.Sequential, Pack=4)]
public struct COR_FIELD_OFFSET
{
public uint ridOfField;
public uint ulOffset;
}
[System.Flags()]
public enum ClassFieldAttribute: uint
{
// member access mask - Use this mask to retrieve accessibility information.
fdFieldAccessMask = 0x0007,
fdPrivateScope = 0x0000, // Member not referenceable.
fdPrivate = 0x0001, // Accessible only by the parent type.
fdFamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly.
fdAssembly = 0x0003, // Accessibly by anyone in the Assembly.
fdFamily = 0x0004, // Accessible only by type and sub-types.
fdFamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly.
fdPublic = 0x0006, // Accessibly by anyone who has visibility to this scope.
// end member access mask
// field contract attributes.
fdStatic = 0x0010, // Defined on type, else per instance.
fdInitOnly = 0x0020, // Field may only be initialized, not written to after init.
fdLiteral = 0x0040, // Value is compile time constant.
fdNotSerialized = 0x0080, // Field does not have to be serialized when type is remoted.
fdSpecialName = 0x0200, // field is special. Name describes how.
// interop attributes
fdPinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke.
// Reserved flags for runtime use only.
fdReservedMask = 0x9500,
fdRTSpecialName = 0x0400, // Runtime(metadata internal APIs) should check name encoding.
fdHasFieldMarshal = 0x1000, // Field has marshalling information.
fdHasDefault = 0x8000, // Field has default.
fdHasFieldRVA = 0x0100, // Field has RVA.
}
public enum CorCallingConvention: uint
{
IMAGE_CEE_CS_CALLCONV_DEFAULT = 0x0,
IMAGE_CEE_CS_CALLCONV_VARARG = 0x5,
IMAGE_CEE_CS_CALLCONV_FIELD = 0x6,
IMAGE_CEE_CS_CALLCONV_LOCAL_SIG = 0x7,
IMAGE_CEE_CS_CALLCONV_PROPERTY = 0x8,
IMAGE_CEE_CS_CALLCONV_UNMGD = 0x9,
IMAGE_CEE_CS_CALLCONV_MAX = 0x10, // first invalid calling convention
// The high bits of the calling convention convey additional info
IMAGE_CEE_CS_CALLCONV_MASK = 0x0f, // Calling convention is bottom 4 bits
IMAGE_CEE_CS_CALLCONV_HASTHIS = 0x20, // Top bit indicates a 'this' parameter
IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS = 0x40, // This parameter is explicitly in the signature
}
public enum CorMethodAttr: uint
{
// member access mask - Use this mask to retrieve accessibility information.
mdMemberAccessMask = 0x0007,
mdPrivateScope = 0x0000, // Member not referenceable.
mdPrivate = 0x0001, // Accessible only by the parent type.
mdFamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly.
mdAssem = 0x0003, // Accessibly by anyone in the Assembly.
mdFamily = 0x0004, // Accessible only by type and sub-types.
mdFamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly.
mdPublic = 0x0006, // Accessibly by anyone who has visibility to this scope.
// end member access mask
// method contract attributes.
mdStatic = 0x0010, // Defined on type, else per instance.
mdFinal = 0x0020, // Method may not be overridden.
mdVirtual = 0x0040, // Method virtual.
mdHideBySig = 0x0080, // Method hides by name+sig, else just by name.
// vtable layout mask - Use this mask to retrieve vtable attributes.
mdVtableLayoutMask = 0x0100,
mdReuseSlot = 0x0000, // The default.
mdNewSlot = 0x0100, // Method always gets a new slot in the vtable.
// end vtable layout mask
// method implementation attributes.
mdCheckAccessOnOverride = 0x0200, // Overridability is the same as the visibility.
mdAbstract = 0x0400, // Method does not provide an implementation.
mdSpecialName = 0x0800, // Method is special. Name describes how.
// interop attributes
mdPinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke.
mdUnmanagedExport = 0x0008, // Managed method exported via thunk to unmanaged code.
// Reserved flags for runtime use only.
mdReservedMask = 0xd000,
mdRTSpecialName = 0x1000, // Runtime should check name encoding.
mdHasSecurity = 0x4000, // Method has security associate with it.
mdRequireSecObject = 0x8000, // Method calls another method containing security code.
}
public enum CorTokenType: uint
{
Module = 0x00000000, //
TypeRef = 0x01000000, //
TypeDef = 0x02000000, //
FieldDef = 0x04000000, //
MethodDef = 0x06000000, //
ParamDef = 0x08000000, //
InterfaceImpl = 0x09000000, //
MemberRef = 0x0a000000, //
CustomAttribute = 0x0c000000, //
Permission = 0x0e000000, //
Signature = 0x11000000, //
Event = 0x14000000, //
Property = 0x17000000, //
ModuleRef = 0x1a000000, //
TypeSpec = 0x1b000000, //
Assembly = 0x20000000, //
AssemblyRef = 0x23000000, //
File = 0x26000000, //
ExportedType = 0x27000000, //
ManifestResource = 0x28000000, //
String = 0x70000000, //
Name = 0x71000000, //
BaseType = 0x72000000, // Leave this on the high end value. This does not correspond to metadata table
}
[ComImport, InterfaceType((short) 1), Guid("7DAC8207-D3AE-4C75-9B67-92801A497D44"), ComConversionLoss]
public interface IMetaDataImport
{
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void CloseEnum(IntPtr hEnum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void CountEnum(IntPtr hEnum, out uint pulCount);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void ResetEnum(IntPtr hEnum, uint ulPos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumTypeDefs(ref IntPtr phEnum, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rTypeDefs, uint cMax, out uint pcTypeDefs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumInterfaceImpls(ref IntPtr phEnum, uint td, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rImpls, uint cMax, out uint pcImpls);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumTypeRefs(ref IntPtr phEnum, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rTypeRefs, uint cMax, out uint pcTypeRefs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void FindTypeDefByName([In, MarshalAs(UnmanagedType.LPWStr)] string szTypeDef, uint tkEnclosingClass, out uint ptd);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetScopeProps(IntPtr szName, uint cchName, out uint pchName, out Guid pmvid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetModuleFromScope(out uint pmd);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, out uint pdwTypeDefFlags, out uint ptkExtends);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetInterfaceImplProps(uint iiImpl, out uint pClass, out uint ptkIface);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetTypeRefProps(uint tr, out uint ptkResolutionScope, IntPtr szName, uint cchName, out uint pchName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppIScope, out uint ptd);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumMembers(ref IntPtr phEnum, uint cl, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rMembers, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumMembersWithName(ref IntPtr phEnum, uint cl, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rMembers, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumMethods(ref IntPtr phEnum, uint cl, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rMethods, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumMethodsWithName(ref IntPtr phEnum, uint cl, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rMethods, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumFields(ref IntPtr phEnum, uint cl, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rFields, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumFieldsWithName(ref IntPtr phEnum, uint cl, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rFields, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumParams(ref IntPtr phEnum, uint mb, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rParams, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumMemberRefs(ref IntPtr phEnum, uint tkParent, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rMemberRefs, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumMethodImpls(ref IntPtr phEnum, uint td, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rMethodBody, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rMethodDecl, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumPermissionSets(ref IntPtr phEnum, uint tk, uint dwActions, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rPermission, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void FindMember(uint td, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, [In] IntPtr pvSigBlob, uint cbSigBlob, out uint pmb);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void FindMethod(uint td, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, [In] IntPtr pvSigBlob, uint cbSigBlob, out uint pmb);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void FindField(uint td, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, [In] IntPtr pvSigBlob, uint cbSigBlob, out uint pmb);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void FindMemberRef(uint td, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, [In] IntPtr pvSigBlob, uint cbSigBlob, out uint pmr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetMemberRefProps(uint mr, out uint ptk, IntPtr szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob, out uint pbSig);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumProperties(ref IntPtr phEnum, uint td, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rProperties, uint cMax, out uint pcProperties);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumEvents(ref IntPtr phEnum, uint td, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rEvents, uint cMax, out uint pcEvents);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetEventProps(uint ev, out uint pClass, IntPtr szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rmdOtherMethod, uint cMax, out uint pcOtherMethod);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumMethodSemantics(ref IntPtr phEnum, uint mb, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rEventProp, uint cMax, out uint pcEventProp);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetMethodSemantics(uint mb, uint tkEventProp, out uint pdwSemanticsFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetClassLayout(uint td, out uint pdwPackSize, [Out] COR_FIELD_OFFSET[] rFieldOffset, uint cMax, out uint pcFieldOffset, out uint pulClassSize);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetFieldMarshal(uint tk, out IntPtr ppvNativeType, out uint pcbNativeType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetRVA(uint tk, out uint pulCodeRVA, out uint pdwImplFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission, out uint pcbPermission);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetSigFromToken(uint mdSig, out IntPtr ppvSig, out uint pcbSig);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetModuleRefProps(uint mur, IntPtr szName, uint cchName, out uint pchName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumModuleRefs(ref IntPtr phEnum, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rModuleRefs, uint cMax, out uint pcModuleRefs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig, out uint pcbSig);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetNameFromToken(uint tk, IntPtr pszUtf8NamePtr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumUnresolvedMethods(ref IntPtr phEnum, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rMethods, uint cMax, out uint pcTokens);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetUserString(uint stk, IntPtr szString, uint cchString, out uint pchString);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetPinvokeMap(uint tk, out uint pdwMappingFlags, IntPtr szImportName, uint cchImportName, out uint pchImportName, out uint pmrImportDLL);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumSignatures(ref IntPtr phEnum, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rSignatures, uint cMax, out uint pcSignatures);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumTypeSpecs(ref IntPtr phEnum, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rTypeSpecs, uint cMax, out uint pcTypeSpecs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumUserStrings(ref IntPtr phEnum, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rStrings, uint cMax, out uint pcStrings);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetParamForMethodIndex(uint md, uint ulParamSeq, out uint ppd);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumCustomAttributes(ref IntPtr phEnum, uint tk, uint tkType, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rCustomAttributes, uint cMax, out uint pcCustomAttributes);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob, out uint pcbSize);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void FindTypeRef(uint tkResolutionScope, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, out uint ptr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetMemberProps(uint mb, out uint pClass, IntPtr szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue, out uint pcchValue);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetFieldProps(uint mb, out uint pClass, [In] IntPtr szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue, out uint pcchValue);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetPropertyProps(uint prop, out uint pClass, IntPtr szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rmdOtherMethod, uint cMax, out uint pcOtherMethod);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetParamProps(uint tk, out uint pmd, out uint pulSequence, IntPtr szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue, out uint pcchValue);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetCustomAttributeByName(uint tkObj, [In, MarshalAs(UnmanagedType.LPWStr)] string szName, out IntPtr ppData, out uint pcbData);
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
int IsValidToken(uint tk);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetNestedClassProps(uint tdNestedClass, out uint ptdEnclosingClass);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetNativeCallConvFromSig([In] IntPtr pvSig, uint cbSig, out uint pCallConv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void IsGlobal(uint pd, out int pbGlobal);
// IMetaDataImport2
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnumGenericParams(ref IntPtr hEnum, uint tk, [Out, MarshalAsAttribute(UnmanagedType.LPArray)] uint[] rGenericParams, uint cMax, out uint pcGenericParams);
void GetGenericParamProps();
void GetMethodSpecProps();
void EnumGenericParamConstraints();
void GetGenericParamConstraintProps();
void GetPEKind();
void GetVersionString();
void EnumMethodSpecs();
}
}
#pragma warning restore 108, 1591

1122
Debugger/Debugger.Core/Interop/MetaDataWrapper.cs

File diff suppressed because it is too large Load Diff

28
Debugger/Debugger.Core/Interop/NativeMethods.cs

@ -0,0 +1,28 @@ @@ -0,0 +1,28 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
#pragma warning disable 1591
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Debugger.Interop
{
public static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("mscoree.dll", CharSet=CharSet.Unicode, PreserveSig=false)]
public static extern Debugger.Interop.CorDebug.ICorDebug CreateDebuggingInterfaceFromVersion(int debuggerVersion, string debuggeeVersion);
[DllImport("mscoree.dll", CharSet=CharSet.Unicode)]
public static extern int GetCORVersion([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szName, Int32 cchBuffer, out Int32 dwLength);
[DllImport("mscoree.dll", CharSet=CharSet.Unicode)]
public static extern int GetRequestedRuntimeVersion(string exeFilename, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pVersion, Int32 cchBuffer, out Int32 dwLength);
}
}
#pragma warning restore 1591

57
Debugger/Debugger.Core/Interop/TrackedComObjects.cs

@ -0,0 +1,57 @@ @@ -0,0 +1,57 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
#pragma warning disable 1591
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Debugger.Interop
{
public static class TrackedComObjects
{
static List<WeakReference> objects = new List<WeakReference>();
public static void ProcessOutParameter(object parameter)
{
if (parameter != null) {
if (Marshal.IsComObject(parameter)) {
Track(parameter);
} else if (parameter is Array) {
foreach(object elem in (Array)parameter) {
ProcessOutParameter(elem);
}
}
}
}
public static void Track(object obj)
{
if (Marshal.IsComObject(obj)) {
lock(objects) {
objects.Add(new WeakReference(obj));
}
}
}
public static int ReleaseAll()
{
lock(objects) {
int count = 0;
foreach(WeakReference weakRef in objects) {
object obj = weakRef.Target;
if (obj != null) {
Marshal.FinalReleaseComObject(obj);
count++;
}
}
objects.Clear();
objects.TrimExcess();
return count;
}
}
}
}
#pragma warning restore 1591

68
Debugger/Debugger.Core/Interop/Util.cs

@ -0,0 +1,68 @@ @@ -0,0 +1,68 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
#pragma warning disable 1591
using System;
using System.Runtime.InteropServices;
namespace Debugger.Interop
{
public delegate void UnmanagedStringGetter(uint pStringLength, out uint stringLength, System.IntPtr pString);
public static class Util
{
const uint DefaultBufferSize = 16;
public static unsafe string GetCorSymString(UnmanagedStringGetter getter)
{
// CorSym does not support truncated result - it thorws exception and does not set actualLength (even with preserve sig)
// ICorDebugStringValue does not support 0 as buffer size
uint actualLength;
getter(0, out actualLength, IntPtr.Zero);
char[] buffer = new char[(int)actualLength];
string managedString;
fixed(char* pBuffer = buffer) {
getter(actualLength, out actualLength, new IntPtr(pBuffer));
managedString = Marshal.PtrToStringUni(new IntPtr(pBuffer), (int)actualLength);
}
managedString = managedString.TrimEnd('\0');
return managedString;
}
public static string GetString(UnmanagedStringGetter getter)
{
return GetString(getter, DefaultBufferSize, true);
}
public static unsafe string GetString(UnmanagedStringGetter getter, uint defaultBufferSize, bool trimNull)
{
string managedString;
// DebugStringValue does not like buffer size of 0
defaultBufferSize = Math.Max(defaultBufferSize, 1);
char[] buffer = new char[(int)defaultBufferSize];
fixed(char* pBuffer = buffer) {
uint actualLength = 0;
getter(defaultBufferSize, out actualLength, new IntPtr(pBuffer));
if(actualLength > defaultBufferSize) {
char[] buffer2 = new char[(int)actualLength];
fixed(char* pBuffer2 = buffer2) {
getter(actualLength, out actualLength, new IntPtr(pBuffer2));
managedString = Marshal.PtrToStringUni(new IntPtr(pBuffer2), (int)actualLength);
}
} else {
managedString = Marshal.PtrToStringUni(new IntPtr(pBuffer), (int)actualLength);
}
}
if (trimNull)
managedString = managedString.TrimEnd('\0');
return managedString;
}
}
}
#pragma warning restore 1591

552
Debugger/Debugger.Core/ManagedCallback.cs

@ -0,0 +1,552 @@ @@ -0,0 +1,552 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Runtime.InteropServices;
using Debugger.Interop;
using Debugger.Interop.CorDebug;
namespace Debugger
{
/// <summary>
/// Handles all callbacks of a given process
/// </summary>
/// <remarks>
/// Note that there can be a queued callback after almost any callback.
/// In particular:
/// - After 'break' there may be more callbacks
/// - After EvalComplete there may be more callbacks (eg CreateThread from other thread)
/// </remarks>
class ManagedCallback
{
Process process;
bool pauseOnNextExit;
bool isInCallback = false;
[Debugger.Tests.Ignore]
public Process Process {
get { return process; }
}
public bool IsInCallback {
get { return isInCallback; }
}
public ManagedCallback(Process process)
{
this.process = process;
}
void EnterCallback(PausedReason pausedReason, string name, ICorDebugProcess pProcess)
{
isInCallback = true;
process.TraceMessage("Callback: " + name);
System.Diagnostics.Debug.Assert(process.CorProcess == pProcess);
// After break is pressed we may receive some messages that were already queued
if (process.IsPaused && process.PauseSession.PausedReason == PausedReason.ForcedBreak) {
// TODO: This does not work well if exception if being processed and the user continues it
process.TraceMessage("Processing post-break callback");
// This compensates for the break call and we are in normal callback handling mode
process.AsyncContinue(DebuggeeStateAction.Keep, new Thread[] {}, null);
// Start of call back - create new pause session (as usual)
process.NotifyPaused(pausedReason);
// Make sure we stay pause after the callback is handled
pauseOnNextExit = true;
return;
}
if (process.IsRunning) {
process.NotifyPaused(pausedReason);
return;
}
throw new DebuggerException("Invalid state at the start of callback");
}
void EnterCallback(PausedReason pausedReason, string name, ICorDebugAppDomain pAppDomain)
{
EnterCallback(pausedReason, name, pAppDomain.GetProcess());
}
void EnterCallback(PausedReason pausedReason, string name, ICorDebugThread pThread)
{
EnterCallback(pausedReason, name, pThread.GetProcess());
process.SelectedThread = process.Threads[pThread];
}
void ExitCallback()
{
bool hasQueuedCallbacks = process.CorProcess.HasQueuedCallbacks();
if (hasQueuedCallbacks)
process.TraceMessage("Process has queued callbacks");
if (hasQueuedCallbacks) {
// Exception has Exception2 queued after it
process.AsyncContinue(DebuggeeStateAction.Keep, null, null);
} else if (process.Evaluating) {
// Ignore events during property evaluation
process.AsyncContinue(DebuggeeStateAction.Keep, null, null);
} else if (pauseOnNextExit) {
if (process.Options.Verbose)
process.TraceMessage("Callback exit: Paused");
pauseOnNextExit = false;
Pause();
} else {
process.AsyncContinue(DebuggeeStateAction.Keep, null, null);
}
isInCallback = false;
}
void Pause()
{
if (process.PauseSession.PausedReason == PausedReason.EvalComplete ||
process.PauseSession.PausedReason == PausedReason.ExceptionIntercepted) {
// TODO: There might be qued callback after EvalComplete making this unrealiable
process.DisableAllSteppers();
process.CheckSelectedStackFrames();
// Do not set selected stack frame
// Do not raise events
} else {
// Raise the pause event outside the callback
// Warning: Make sure that process in not resumed in the meantime
process.Debugger.MTA2STA.AsyncCall(process.RaisePausedEvents);
// The event might probably get called out of order when the process is running again
}
}
#region Program folow control
public void StepComplete(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugStepper pStepper, CorDebugStepReason reason)
{
EnterCallback(PausedReason.StepComplete, "StepComplete (" + reason.ToString() + ")", pThread);
Thread thread = process.Threads[pThread];
Stepper stepper = process.GetStepper(pStepper);
StackFrame currentStackFrame = process.SelectedThread.MostRecentStackFrame;
process.TraceMessage(" - stopped at {0} because of {1}", currentStackFrame.MethodInfo.FullName, stepper.ToString());
process.Steppers.Remove(stepper);
stepper.OnStepComplete(reason);
if (stepper.Ignore) {
// The stepper is ignored
process.TraceMessage(" - ignored");
} else if (thread.CurrentStepIn != null &&
thread.CurrentStepIn.StackFrame.Equals(currentStackFrame) &&
thread.CurrentStepIn.IsInStepRanges((int)currentStackFrame.IP)) {
Stepper.StepIn(currentStackFrame, thread.CurrentStepIn.StepRanges, "finishing step in");
process.TraceMessage(" - finishing step in");
} else if (currentStackFrame.MethodInfo.StepOver) {
if (process.Options.EnableJustMyCode) {
currentStackFrame.MethodInfo.MarkAsNonUserCode();
process.TraceMessage(" - method {0} marked as non user code", currentStackFrame.MethodInfo.FullName);
Stepper.StepIn(currentStackFrame, new int[] {0, int.MaxValue}, "seeking user code");
process.TraceMessage(" - seeking user code");
} else {
Stepper.StepOut(currentStackFrame, "stepping out of non-user code");
process.TraceMessage(" - stepping out of non-user code");
}
} else {
// User-code method
pauseOnNextExit = true;
process.TraceMessage(" - pausing in user code");
}
ExitCallback();
}
// Warning! Marshaing of ICorBreakpoint fails in .NET 1.1
public void Breakpoint(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugBreakpoint corBreakpoint)
{
EnterCallback(PausedReason.Breakpoint, "Breakpoint", pThread);
Breakpoint breakpoint = process.Debugger.Breakpoints[corBreakpoint];
// The event will be risen outside the callback
process.BreakpointHitEventQueue.Enqueue(breakpoint);
pauseOnNextExit = true;
ExitCallback();
}
public void BreakpointSetError(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugBreakpoint pBreakpoint, uint dwError)
{
EnterCallback(PausedReason.Other, "BreakpointSetError", pThread);
ExitCallback();
}
public void Break(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread)
{
EnterCallback(PausedReason.Break, "Break", pThread);
pauseOnNextExit = true;
ExitCallback();
}
public void ControlCTrap(ICorDebugProcess pProcess)
{
EnterCallback(PausedReason.ControlCTrap, "ControlCTrap", pProcess);
pauseOnNextExit = true;
ExitCallback();
}
public void Exception(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, int unhandled)
{
// Exception2 is used in .NET Framework 2.0
if (process.DebuggeeVersion.StartsWith("v1.")) {
// Forward the call to Exception2, which handles EnterCallback and ExitCallback
ExceptionType exceptionType = (unhandled != 0) ? ExceptionType.Unhandled : ExceptionType.FirstChance;
Exception2(pAppDomain, pThread, null, 0, (CorDebugExceptionCallbackType)exceptionType, 0);
} else {
// This callback should be ignored in v2 applications
EnterCallback(PausedReason.Other, "Exception", pThread);
ExitCallback();
}
}
#endregion
#region Various
public void LogSwitch(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, int lLevel, uint ulReason, string pLogSwitchName, string pParentName)
{
EnterCallback(PausedReason.Other, "LogSwitch", pThread);
ExitCallback();
}
public void LogMessage(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, int lLevel, string pLogSwitchName, string pMessage)
{
EnterCallback(PausedReason.Other, "LogMessage", pThread);
process.OnLogMessage(new MessageEventArgs(process, lLevel, pMessage, pLogSwitchName));
ExitCallback();
}
public void EditAndContinueRemap(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugFunction pFunction, int fAccurate)
{
EnterCallback(PausedReason.Other, "EditAndContinueRemap", pThread);
ExitCallback();
}
public void EvalException(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugEval corEval)
{
EnterCallback(PausedReason.EvalComplete, "EvalException", pThread);
HandleEvalComplete(pAppDomain, pThread, corEval, true);
}
public void EvalComplete(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugEval corEval)
{
EnterCallback(PausedReason.EvalComplete, "EvalComplete", pThread);
HandleEvalComplete(pAppDomain, pThread, corEval, false);
}
void HandleEvalComplete(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugEval corEval, bool exception)
{
// Let the eval know that the CorEval has finished
Eval eval = process.ActiveEvals[corEval];
eval.NotifyEvaluationComplete(!exception);
process.ActiveEvals.Remove(eval);
pauseOnNextExit = true;
ExitCallback();
}
public void DebuggerError(ICorDebugProcess pProcess, int errorHR, uint errorCode)
{
EnterCallback(PausedReason.DebuggerError, "DebuggerError", pProcess);
string errorText = String.Format("Debugger error: \nHR = 0x{0:X} \nCode = 0x{1:X}", errorHR, errorCode);
if ((uint)errorHR == 0x80131C30) {
errorText += "\n\nDebugging 64-bit processes is currently not supported.\n" +
"If you are running a 64-bit system, this setting might help:\n" +
"Project -> Project Options -> Compiling -> Target CPU = 32-bit Intel";
}
if (Environment.UserInteractive)
System.Windows.Forms.MessageBox.Show(errorText);
else
throw new DebuggerException(errorText);
try {
pauseOnNextExit = true;
ExitCallback();
} catch (COMException) {
} catch (InvalidComObjectException) {
// ignore errors during shutdown after debugger error
}
}
public void UpdateModuleSymbols(ICorDebugAppDomain pAppDomain, ICorDebugModule pModule, IStream pSymbolStream)
{
EnterCallback(PausedReason.Other, "UpdateModuleSymbols", pAppDomain);
Module module = process.Modules[pModule];
if (module.CorModule is ICorDebugModule3 && module.IsDynamic) {
// In .NET 4.0, we use the LoadClass callback to load dynamic modules
// because it always works - UpdateModuleSymbols does not.
// - Simple dynamic code generation seems to trigger both callbacks.
// - IronPython for some reason causes just the LoadClass callback
// so we choose to rely on it out of the two.
} else {
// In .NET 2.0, this is the the only method and it works fine
module.LoadSymbolsFromMemory(pSymbolStream);
}
ExitCallback();
}
#endregion
#region Start of Application
public void CreateProcess(ICorDebugProcess pProcess)
{
EnterCallback(PausedReason.Other, "CreateProcess", pProcess);
// Process is added in NDebugger.Start
ExitCallback();
}
public void CreateAppDomain(ICorDebugProcess pProcess, ICorDebugAppDomain pAppDomain)
{
EnterCallback(PausedReason.Other, "CreateAppDomain", pAppDomain);
pAppDomain.Attach();
process.AppDomains.Add(new AppDomain(process, pAppDomain));
ExitCallback();
}
public void LoadAssembly(ICorDebugAppDomain pAppDomain, ICorDebugAssembly pAssembly)
{
EnterCallback(PausedReason.Other, "LoadAssembly", pAppDomain);
ExitCallback();
}
public void LoadModule(ICorDebugAppDomain pAppDomain, ICorDebugModule pModule)
{
EnterCallback(PausedReason.Other, "LoadModule " + pModule.GetName(), pAppDomain);
Module module = new Module(process.AppDomains[pAppDomain], pModule);
process.Modules.Add(module);
ExitCallback();
}
public void NameChange(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread)
{
if (pAppDomain != null) {
EnterCallback(PausedReason.Other, "NameChange: pAppDomain", pAppDomain);
ExitCallback();
}
if (pThread != null) {
EnterCallback(PausedReason.Other, "NameChange: pThread", pThread);
Thread thread = process.Threads[pThread];
thread.NotifyNameChanged();
ExitCallback();
}
}
public void CreateThread(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread)
{
// We can not use pThread since it has not been added yet
// and we continue from this callback anyway
EnterCallback(PausedReason.Other, "CreateThread " + pThread.GetID(), pAppDomain);
Thread thread = new Thread(process, pThread);
process.Threads.Add(thread);
thread.CorThread.SetDebugState(process.NewThreadState);
ExitCallback();
}
public void LoadClass(ICorDebugAppDomain pAppDomain, ICorDebugClass c)
{
EnterCallback(PausedReason.Other, "LoadClass", pAppDomain);
Module module = process.Modules[c.GetModule()];
// Dynamic module has been extended - reload symbols to inlude new class
module.LoadSymbolsDynamic();
ExitCallback();
}
#endregion
#region Exit of Application
public void UnloadClass(ICorDebugAppDomain pAppDomain, ICorDebugClass c)
{
EnterCallback(PausedReason.Other, "UnloadClass", pAppDomain);
ExitCallback();
}
public void UnloadModule(ICorDebugAppDomain pAppDomain, ICorDebugModule pModule)
{
EnterCallback(PausedReason.Other, "UnloadModule", pAppDomain);
process.Modules.Remove(process.Modules[pModule]);
ExitCallback();
}
public void UnloadAssembly(ICorDebugAppDomain pAppDomain, ICorDebugAssembly pAssembly)
{
EnterCallback(PausedReason.Other, "UnloadAssembly", pAppDomain);
ExitCallback();
}
public void ExitThread(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread)
{
// ICorDebugThread is still not dead and can be used for some operations
if (process.Threads.Contains(pThread)) {
EnterCallback(PausedReason.Other, "ExitThread " + pThread.GetID(), pThread);
process.Threads[pThread].NotifyExited();
} else {
EnterCallback(PausedReason.Other, "ExitThread " + pThread.GetID(), process.CorProcess);
// .NET 4.0 - It seems that the API is reporting exits of threads without announcing their creation.
// TODO: Remove in next .NET 4.0 beta and investigate
process.TraceMessage("ERROR: Thread does not exist " + pThread.GetID());
}
try {
ExitCallback();
} catch (COMException e) {
// For some reason this sometimes happens in .NET 1.1
process.TraceMessage("Continue failed in ExitThread callback: " + e.Message);
}
}
public void ExitAppDomain(ICorDebugProcess pProcess, ICorDebugAppDomain pAppDomain)
{
EnterCallback(PausedReason.Other, "ExitAppDomain", pAppDomain);
process.AppDomains.Remove(process.AppDomains[pAppDomain]);
ExitCallback();
}
public void ExitProcess(ICorDebugProcess pProcess)
{
// ExitProcess may be called at any time when debuggee is killed
process.TraceMessage("Callback: ExitProcess");
process.NotifyHasExited();
}
#endregion
#region ICorDebugManagedCallback2 Members
public void ChangeConnection(ICorDebugProcess pProcess, uint dwConnectionId)
{
EnterCallback(PausedReason.Other, "ChangeConnection", pProcess);
ExitCallback();
}
public void CreateConnection(ICorDebugProcess pProcess, uint dwConnectionId, IntPtr pConnName)
{
EnterCallback(PausedReason.Other, "CreateConnection", pProcess);
ExitCallback();
}
public void DestroyConnection(ICorDebugProcess pProcess, uint dwConnectionId)
{
EnterCallback(PausedReason.Other, "DestroyConnection", pProcess);
ExitCallback();
}
public void Exception2(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugFrame pFrame, uint nOffset, CorDebugExceptionCallbackType exceptionType, uint dwFlags)
{
EnterCallback(PausedReason.Exception, "Exception2 (type=" + exceptionType.ToString() + ")", pThread);
// This callback is also called from Exception(...)!!!! (the .NET 1.1 version)
// Watch out for the zeros and null!
// Exception -> Exception2(pAppDomain, pThread, null, 0, exceptionType, 0);
if ((ExceptionType)exceptionType == ExceptionType.Unhandled || process.PauseOnHandledException) {
process.SelectedThread.CurrentException = new Exception(new Value(process.AppDomains[pAppDomain], process.SelectedThread.CorThread.GetCurrentException()).GetPermanentReference());
process.SelectedThread.CurrentException_DebuggeeState = process.DebuggeeState;
process.SelectedThread.CurrentExceptionType = (ExceptionType)exceptionType;
process.SelectedThread.CurrentExceptionIsUnhandled = (ExceptionType)exceptionType == ExceptionType.Unhandled;
pauseOnNextExit = true;
}
ExitCallback();
}
public void ExceptionUnwind(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, CorDebugExceptionUnwindCallbackType dwEventType, uint dwFlags)
{
EnterCallback(PausedReason.ExceptionIntercepted, "ExceptionUnwind", pThread);
if (dwEventType == CorDebugExceptionUnwindCallbackType.DEBUG_EXCEPTION_INTERCEPTED) {
pauseOnNextExit = true;
}
ExitCallback();
}
public void FunctionRemapComplete(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugFunction pFunction)
{
EnterCallback(PausedReason.Other, "FunctionRemapComplete", pThread);
ExitCallback();
}
public void FunctionRemapOpportunity(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugFunction pOldFunction, ICorDebugFunction pNewFunction, uint oldILOffset)
{
EnterCallback(PausedReason.Other, "FunctionRemapOpportunity", pThread);
ExitCallback();
}
/// <exception cref="Exception">Unknown callback argument</exception>
public void MDANotification(ICorDebugController c, ICorDebugThread t, ICorDebugMDA mda)
{
if (c is ICorDebugAppDomain) {
EnterCallback(PausedReason.Other, "MDANotification", (ICorDebugAppDomain)c);
} else if (c is ICorDebugProcess){
EnterCallback(PausedReason.Other, "MDANotification", (ICorDebugProcess)c);
} else {
throw new System.Exception("Unknown callback argument");
}
ExitCallback();
}
#endregion
}
}

420
Debugger/Debugger.Core/ManagedCallbackProxy.cs

@ -0,0 +1,420 @@ @@ -0,0 +1,420 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Windows.Forms;
using Debugger.Interop;
using Debugger.Interop.CorDebug;
// Regular expresion:
// ^{\t*}{(:Ll| )*{:i} *\(((.# {:i}, |\))|())^6\)*}\n\t*\{(.|\n)@\t\}
// Output: \1 - intention \2 - declaration \3 - function name \4-9 parameters
// Replace with:
// \1\2\n\1{\n\1\tCallbackReceived("\3", new object[] {\4, \5, \6, \7, \8, \9});\n\1}
// \1\2\n\1{\n\1\tCall(delegate {\n\1\t \trealCallback.\3(\n\1\t \t\tMTA2STA.MarshalIntPtrTo(\4),\n\1\t \t\tMTA2STA.MarshalIntPtrTo(\5),\n\1\t \t\tMTA2STA.MarshalIntPtrTo(\6),\n\1\t \t\tMTA2STA.MarshalIntPtrTo(\7),\n\1\t \t\tMTA2STA.MarshalIntPtrTo(\8),\n\1\t \t\tMTA2STA.MarshalIntPtrTo(\9),\n\1\t \t);\n\1\t });\n\1}
namespace Debugger
{
/// <summary>
/// This proxy marshals the callback to the appropriate thread
/// </summary>
class ManagedCallbackProxy : ICorDebugManagedCallback, ICorDebugManagedCallback2
{
NDebugger debugger;
ManagedCallbackSwitch callbackSwitch;
public NDebugger Debugger {
get {
return debugger;
}
}
public ManagedCallbackProxy(NDebugger debugger, ManagedCallbackSwitch callbackSwitch)
{
this.debugger = debugger;
this.callbackSwitch = callbackSwitch;
}
void Call(MethodInvoker callback)
{
debugger.MTA2STA.Call(callback);
}
public void StepComplete(System.IntPtr pAppDomain, System.IntPtr pThread, System.IntPtr pStepper, CorDebugStepReason reason)
{
Call(delegate {
callbackSwitch.StepComplete(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugStepper>(pStepper),
reason
);
});
}
public void Break(System.IntPtr pAppDomain, System.IntPtr pThread)
{
Call(delegate {
callbackSwitch.Break(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread)
);
});
}
public void ControlCTrap(System.IntPtr pProcess)
{
Call(delegate {
callbackSwitch.ControlCTrap(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess)
);
});
}
public void Exception(System.IntPtr pAppDomain, System.IntPtr pThread, int unhandled)
{
Call(delegate {
callbackSwitch.Exception(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
unhandled
);
});
}
public void Breakpoint(System.IntPtr pAppDomain, System.IntPtr pThread, System.IntPtr pBreakpoint)
{
Call(delegate {
callbackSwitch.Breakpoint(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
// This fails in .NET 1.1:
MTA2STA.MarshalIntPtrTo<ICorDebugBreakpoint>(pBreakpoint)
);
});
}
public void CreateProcess(System.IntPtr pProcess)
{
Call(delegate {
callbackSwitch.CreateProcess(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess)
);
});
}
public void CreateAppDomain(System.IntPtr pProcess, System.IntPtr pAppDomain)
{
Call(delegate {
callbackSwitch.CreateAppDomain(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess),
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain)
);
});
}
public void CreateThread(System.IntPtr pAppDomain, System.IntPtr pThread)
{
Call(delegate {
callbackSwitch.CreateThread(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread)
);
});
}
public void LoadAssembly(System.IntPtr pAppDomain, System.IntPtr pAssembly)
{
Call(delegate {
callbackSwitch.LoadAssembly(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugAssembly>(pAssembly)
);
});
}
public void LoadModule(System.IntPtr pAppDomain, System.IntPtr pModule)
{
Call(delegate {
callbackSwitch.LoadModule(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugModule>(pModule)
);
});
}
public void NameChange(System.IntPtr pAppDomain, System.IntPtr pThread)
{
Call(delegate {
callbackSwitch.NameChange(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread)
);
});
}
public void LoadClass(System.IntPtr pAppDomain, System.IntPtr c)
{
Call(delegate {
callbackSwitch.LoadClass(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugClass>(c)
);
});
}
public void UnloadClass(System.IntPtr pAppDomain, System.IntPtr c)
{
Call(delegate {
callbackSwitch.UnloadClass(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugClass>(c)
);
});
}
public void ExitThread(System.IntPtr pAppDomain, System.IntPtr pThread)
{
Call(delegate {
callbackSwitch.ExitThread(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread)
);
});
}
public void UnloadModule(System.IntPtr pAppDomain, System.IntPtr pModule)
{
Call(delegate {
callbackSwitch.UnloadModule(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugModule>(pModule)
);
});
}
public void UnloadAssembly(System.IntPtr pAppDomain, System.IntPtr pAssembly)
{
Call(delegate {
callbackSwitch.UnloadAssembly(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugAssembly>(pAssembly)
);
});
}
public void ExitAppDomain(System.IntPtr pProcess, System.IntPtr pAppDomain)
{
Call(delegate {
callbackSwitch.ExitAppDomain(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess),
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain)
);
});
}
public void ExitProcess(System.IntPtr pProcess)
{
Call(delegate {
callbackSwitch.ExitProcess(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess)
);
});
}
public void BreakpointSetError(System.IntPtr pAppDomain, System.IntPtr pThread, System.IntPtr pBreakpoint, uint dwError)
{
Call(delegate {
callbackSwitch.BreakpointSetError(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugBreakpoint>(pBreakpoint),
dwError
);
});
}
public void LogSwitch(System.IntPtr pAppDomain, System.IntPtr pThread, int lLevel, uint ulReason, System.IntPtr pLogSwitchName, System.IntPtr pParentName)
{
Call(delegate {
callbackSwitch.LogSwitch(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
lLevel,
ulReason,
MTA2STA.MarshalIntPtrTo<string>(pLogSwitchName),
MTA2STA.MarshalIntPtrTo<string>(pParentName)
);
});
}
public void EvalException(System.IntPtr pAppDomain, System.IntPtr pThread, System.IntPtr pEval)
{
Call(delegate {
callbackSwitch.EvalException(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugEval>(pEval)
);
});
}
public void LogMessage(System.IntPtr pAppDomain, System.IntPtr pThread, int lLevel, System.IntPtr pLogSwitchName, System.IntPtr pMessage)
{
Call(delegate {
callbackSwitch.LogMessage(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
lLevel,
MTA2STA.MarshalIntPtrTo<string>(pLogSwitchName),
MTA2STA.MarshalIntPtrTo<string>(pMessage)
);
});
}
public void EditAndContinueRemap(System.IntPtr pAppDomain, System.IntPtr pThread, System.IntPtr pFunction, int fAccurate)
{
Call(delegate {
callbackSwitch.EditAndContinueRemap(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugFunction>(pFunction),
fAccurate
);
});
}
public void EvalComplete(System.IntPtr pAppDomain, System.IntPtr pThread, System.IntPtr pEval)
{
Call(delegate {
callbackSwitch.EvalComplete(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugEval>(pEval)
);
});
}
public void DebuggerError(System.IntPtr pProcess, int errorHR, uint errorCode)
{
Call(delegate {
callbackSwitch.DebuggerError(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess),
errorHR,
errorCode
);
});
}
public void UpdateModuleSymbols(System.IntPtr pAppDomain, System.IntPtr pModule, System.IntPtr pSymbolStream)
{
Call(delegate {
callbackSwitch.UpdateModuleSymbols(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugModule>(pModule),
MTA2STA.MarshalIntPtrTo<IStream>(pSymbolStream)
);
});
}
#region ICorDebugManagedCallback2 Members
public void ChangeConnection(IntPtr pProcess, uint dwConnectionId)
{
Call(delegate {
callbackSwitch.ChangeConnection(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess),
dwConnectionId
);
});
}
public void CreateConnection(IntPtr pProcess, uint dwConnectionId, IntPtr pConnName)
{
Call(delegate {
callbackSwitch.CreateConnection(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess),
dwConnectionId,
pConnName
);
});
}
public void DestroyConnection(IntPtr pProcess, uint dwConnectionId)
{
Call(delegate {
callbackSwitch.DestroyConnection(
MTA2STA.MarshalIntPtrTo<ICorDebugProcess>(pProcess),
dwConnectionId
);
});
}
public void Exception(IntPtr pAppDomain, IntPtr pThread, IntPtr pFrame, uint nOffset, CorDebugExceptionCallbackType dwEventType, uint dwFlags)
{
Call(delegate {
callbackSwitch.Exception2(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugFrame>(pFrame),
nOffset,
dwEventType,
dwFlags
);
});
}
public void ExceptionUnwind(IntPtr pAppDomain, IntPtr pThread, CorDebugExceptionUnwindCallbackType dwEventType, uint dwFlags)
{
Call(delegate {
callbackSwitch.ExceptionUnwind(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
dwEventType,
dwFlags
);
});
}
public void FunctionRemapComplete(IntPtr pAppDomain, IntPtr pThread, IntPtr pFunction)
{
Call(delegate {
callbackSwitch.FunctionRemapComplete(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugFunction>(pFunction)
);
});
}
public void FunctionRemapOpportunity(IntPtr pAppDomain, IntPtr pThread, IntPtr pOldFunction, IntPtr pNewFunction, uint oldILOffset)
{
Call(delegate {
callbackSwitch.FunctionRemapOpportunity(
MTA2STA.MarshalIntPtrTo<ICorDebugAppDomain>(pAppDomain),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugFunction>(pOldFunction),
MTA2STA.MarshalIntPtrTo<ICorDebugFunction>(pNewFunction),
oldILOffset
);
});
}
public void MDANotification(IntPtr pController, IntPtr pThread, IntPtr pMDA)
{
Call(delegate {
callbackSwitch.MDANotification(
MTA2STA.MarshalIntPtrTo<ICorDebugController>(pController),
MTA2STA.MarshalIntPtrTo<ICorDebugThread>(pThread),
MTA2STA.MarshalIntPtrTo<ICorDebugMDA>(pMDA)
);
});
}
#endregion
}
}

400
Debugger/Debugger.Core/ManagedCallbackSwitch.cs

@ -0,0 +1,400 @@ @@ -0,0 +1,400 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
// Regular expresion:
// ^{\t*}{(:Ll| )*{:i} *\(((.# {:i}, |\))|())^6\)*}\n\t*\{(.|\n)@^\1\}
// Output: \1 - intention \2 - declaration \3 - function name \4-9 parameters
// Replace with:
// \1\2\n\1{\n\1\tGetProcessCallbackInterface(\4).\3(\4, \5, \6, \7, \8, \9);\n\1}
using System;
using System.Runtime.InteropServices;
using Debugger.Interop;
using Debugger.Interop.CorDebug;
namespace Debugger
{
/// <summary>
/// This class forwards the callback the the approprite process
/// </summary>
class ManagedCallbackSwitch
{
NDebugger debugger;
public NDebugger Debugger {
get {
return debugger;
}
}
public ManagedCallbackSwitch(NDebugger debugger)
{
this.debugger = debugger;
}
public ManagedCallback GetProcessCallbackInterface(string name, ICorDebugController c)
{
if (c is ICorDebugAppDomain) {
return GetProcessCallbackInterface(name, (ICorDebugAppDomain)c);
} else if (c is ICorDebugProcess){
return GetProcessCallbackInterface(name, (ICorDebugProcess)c);
} else {
throw new System.Exception("Unknown callback argument");
}
}
public ManagedCallback GetProcessCallbackInterface(string name, ICorDebugThread pThread)
{
ICorDebugProcess pProcess;
try {
pProcess = pThread.GetProcess();
} catch (COMException e) {
debugger.TraceMessage("Ignoring callback \"" + name + "\": " + e.Message);
return null;
}
return GetProcessCallbackInterface(name, pProcess);
}
public ManagedCallback GetProcessCallbackInterface(string name, ICorDebugAppDomain pAppDomain)
{
ICorDebugProcess pProcess;
try {
pProcess = pAppDomain.GetProcess();
} catch (COMException e) {
debugger.TraceMessage("Ignoring callback \"" + name + "\": " + e.Message);
return null;
}
return GetProcessCallbackInterface(name, pProcess);
}
public ManagedCallback GetProcessCallbackInterface(string name, ICorDebugProcess pProcess)
{
Process process;
// We have to wait until the created process is added into the collection
lock(debugger.ProcessIsBeingCreatedLock) {
process = debugger.Processes[pProcess];
}
// Make *really* sure the process is not dead
if (process == null) {
debugger.TraceMessage("Ignoring callback \"" + name + "\": Process not found");
return null;
}
if (process.HasExited) {
debugger.TraceMessage("Ignoring callback \"" + name + "\": Process has exited");
return null;
}
if (process.TerminateCommandIssued && !(name == "ExitProcess")) {
debugger.TraceMessage("Ignoring callback \"" + name + "\": Terminate command was issued for the process");
return null;
}
// Check that the process is not exited
try {
int isRunning = process.CorProcess.IsRunning();
} catch (COMException e) {
process.TraceMessage("Ignoring callback \"" + name + "\": " + e.Message);
return null;
}
return process.CallbackInterface;
}
public void ExitProcess(ICorDebugProcess pProcess)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("ExitProcess", pProcess);
if (managedCallback != null) {
managedCallback.ExitProcess(pProcess);
}
}
#region Program folow control
public void StepComplete(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugStepper pStepper, CorDebugStepReason reason)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("StepComplete", pAppDomain);
if (managedCallback != null) {
managedCallback.StepComplete(pAppDomain, pThread, pStepper, reason);
}
}
// Do not pass the pBreakpoint parameter as ICorDebugBreakpoint - marshaling of it fails in .NET 1.1
public void Breakpoint(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugBreakpoint pBreakpoint)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("Breakpoint", pAppDomain);
if (managedCallback != null) {
managedCallback.Breakpoint(pAppDomain, pThread, pBreakpoint);
}
}
public void BreakpointSetError(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugBreakpoint pBreakpoint, uint dwError)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("BreakpointSetError", pAppDomain);
if (managedCallback != null) {
managedCallback.BreakpointSetError(pAppDomain, pThread, pBreakpoint, dwError);
}
}
public unsafe void Break(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("Break", pAppDomain);
if (managedCallback != null) {
managedCallback.Break(pAppDomain, pThread);
}
}
public void ControlCTrap(ICorDebugProcess pProcess)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("ControlCTrap", pProcess);
if (managedCallback != null) {
managedCallback.ControlCTrap(pProcess);
}
}
public unsafe void Exception(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, int unhandled)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("Exception", pAppDomain);
if (managedCallback != null) {
managedCallback.Exception(pAppDomain, pThread, unhandled);
}
}
#endregion
#region Various
public void LogSwitch(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, int lLevel, uint ulReason, string pLogSwitchName, string pParentName)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("LogSwitch", pAppDomain);
if (managedCallback != null) {
managedCallback.LogSwitch(pAppDomain, pThread, lLevel, ulReason, pLogSwitchName, pParentName);
}
}
public void LogMessage(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, int lLevel, string pLogSwitchName, string pMessage)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("LogMessage", pAppDomain);
if (managedCallback != null) {
managedCallback.LogMessage(pAppDomain, pThread, lLevel, pLogSwitchName, pMessage);
}
}
public void EditAndContinueRemap(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugFunction pFunction, int fAccurate)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("EditAndContinueRemap", pAppDomain);
if (managedCallback != null) {
managedCallback.EditAndContinueRemap(pAppDomain, pThread, pFunction, fAccurate);
}
}
public void EvalException(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugEval corEval)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("EvalException", pAppDomain);
if (managedCallback != null) {
managedCallback.EvalException(pAppDomain, pThread, corEval);
}
}
public void EvalComplete(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugEval corEval)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("EvalComplete", pAppDomain);
if (managedCallback != null) {
managedCallback.EvalComplete(pAppDomain, pThread, corEval);
}
}
public void DebuggerError(ICorDebugProcess pProcess, int errorHR, uint errorCode)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("DebuggerError", pProcess);
if (managedCallback != null) {
managedCallback.DebuggerError(pProcess, errorHR, errorCode);
}
}
public void UpdateModuleSymbols(ICorDebugAppDomain pAppDomain, ICorDebugModule pModule, IStream pSymbolStream)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("UpdateModuleSymbols", pAppDomain);
if (managedCallback != null) {
managedCallback.UpdateModuleSymbols(pAppDomain, pModule, pSymbolStream);
}
}
#endregion
#region Start of Application
public void CreateProcess(ICorDebugProcess pProcess)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("CreateProcess", pProcess);
if (managedCallback != null) {
managedCallback.CreateProcess(pProcess);
}
}
public void CreateAppDomain(ICorDebugProcess pProcess, ICorDebugAppDomain pAppDomain)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("CreateAppDomain", pProcess);
if (managedCallback != null) {
managedCallback.CreateAppDomain(pProcess, pAppDomain);
}
}
public void LoadAssembly(ICorDebugAppDomain pAppDomain, ICorDebugAssembly pAssembly)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("LoadAssembly", pAppDomain);
if (managedCallback != null) {
managedCallback.LoadAssembly(pAppDomain, pAssembly);
}
}
public unsafe void LoadModule(ICorDebugAppDomain pAppDomain, ICorDebugModule pModule)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("LoadModule", pAppDomain);
if (managedCallback != null) {
managedCallback.LoadModule(pAppDomain, pModule);
}
}
public void NameChange(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread)
{
ManagedCallback managedCallback = null;
if (pAppDomain != null) {
managedCallback = GetProcessCallbackInterface("NameChange", pAppDomain);
}
if (pThread != null) {
managedCallback = GetProcessCallbackInterface("NameChange", pThread);
}
if (managedCallback != null) {
managedCallback.NameChange(pAppDomain, pThread);
}
}
public void CreateThread(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("CreateThread", pAppDomain);
if (managedCallback != null) {
managedCallback.CreateThread(pAppDomain, pThread);
}
}
public void LoadClass(ICorDebugAppDomain pAppDomain, ICorDebugClass c)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("LoadClass", pAppDomain);
if (managedCallback != null) {
managedCallback.LoadClass(pAppDomain, c);
}
}
#endregion
#region Exit of Application
public void UnloadClass(ICorDebugAppDomain pAppDomain, ICorDebugClass c)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("UnloadClass", pAppDomain);
if (managedCallback != null) {
managedCallback.UnloadClass(pAppDomain, c);
}
}
public void UnloadModule(ICorDebugAppDomain pAppDomain, ICorDebugModule pModule)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("UnloadModule", pAppDomain);
if (managedCallback != null) {
managedCallback.UnloadModule(pAppDomain, pModule);
}
}
public void UnloadAssembly(ICorDebugAppDomain pAppDomain, ICorDebugAssembly pAssembly)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("UnloadAssembly", pAppDomain);
if (managedCallback != null) {
managedCallback.UnloadAssembly(pAppDomain, pAssembly);
}
}
public void ExitThread(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("ExitThread", pAppDomain);
if (managedCallback != null) {
managedCallback.ExitThread(pAppDomain, pThread);
}
}
public void ExitAppDomain(ICorDebugProcess pProcess, ICorDebugAppDomain pAppDomain)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("ExitAppDomain", pProcess);
if (managedCallback != null) {
managedCallback.ExitAppDomain(pProcess, pAppDomain);
}
}
#endregion
#region ICorDebugManagedCallback2 Members
public void ChangeConnection(ICorDebugProcess pProcess, uint dwConnectionId)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("ChangeConnection", pProcess);
if (managedCallback != null) {
managedCallback.ChangeConnection(pProcess, dwConnectionId);
}
}
public void CreateConnection(ICorDebugProcess pProcess, uint dwConnectionId, IntPtr pConnName)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("CreateConnection", pProcess);
if (managedCallback != null) {
managedCallback.CreateConnection(pProcess, dwConnectionId, pConnName);
}
}
public void DestroyConnection(ICorDebugProcess pProcess, uint dwConnectionId)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("DestroyConnection", pProcess);
if (managedCallback != null) {
managedCallback.DestroyConnection(pProcess, dwConnectionId);
}
}
public void Exception2(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugFrame pFrame, uint nOffset, CorDebugExceptionCallbackType exceptionType, uint dwFlags)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("Exception2", pAppDomain);
if (managedCallback != null) {
managedCallback.Exception2(pAppDomain, pThread, pFrame, nOffset, exceptionType, dwFlags);
}
}
public void ExceptionUnwind(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, CorDebugExceptionUnwindCallbackType dwEventType, uint dwFlags)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("ExceptionUnwind", pAppDomain);
if (managedCallback != null) {
managedCallback.ExceptionUnwind(pAppDomain, pThread, dwEventType, dwFlags);
}
}
public void FunctionRemapComplete(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugFunction pFunction)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("FunctionRemapComplete", pAppDomain);
if (managedCallback != null) {
managedCallback.FunctionRemapComplete(pAppDomain, pThread, pFunction);
}
}
public void FunctionRemapOpportunity(ICorDebugAppDomain pAppDomain, ICorDebugThread pThread, ICorDebugFunction pOldFunction, ICorDebugFunction pNewFunction, uint oldILOffset)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("FunctionRemapOpportunity", pAppDomain);
if (managedCallback != null) {
managedCallback.FunctionRemapOpportunity(pAppDomain, pThread, pOldFunction, pNewFunction, oldILOffset);
}
}
public void MDANotification(ICorDebugController c, ICorDebugThread t, ICorDebugMDA mda)
{
ManagedCallback managedCallback = GetProcessCallbackInterface("MDANotification", c);
if (managedCallback != null) {
managedCallback.MDANotification(c, t, mda);
}
}
#endregion
}
}

133
Debugger/Debugger.Core/MetaData/DebugConstructorInfo.cs

@ -0,0 +1,133 @@ @@ -0,0 +1,133 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Debugger.Interop.CorDebug;
using Debugger.Interop.CorSym;
using Debugger.Interop.MetaData;
using Mono.Cecil.Signatures;
namespace Debugger.MetaData
{
public class DebugConstructorInfo: System.Reflection.ConstructorInfo, IDebugMemberInfo
{
DebugMethodInfo methodInfo;
internal DebugConstructorInfo(DebugMethodInfo methodInfo)
{
this.methodInfo = methodInfo;
}
Debugger.Module IDebugMemberInfo.DebugModule {
get { return methodInfo.DebugModule; }
}
/// <inheritdoc/>
public override Type DeclaringType {
get { return methodInfo.DeclaringType; }
}
/// <inheritdoc/>
public override int MetadataToken {
get { return methodInfo.MetadataToken; }
}
/// <inheritdoc/>
public override System.Reflection.Module Module {
get { return methodInfo.Module; }
}
/// <inheritdoc/>
public override string Name {
get { return methodInfo.Name; }
}
/// <inheritdoc/>
public override Type ReflectedType {
get { return methodInfo.ReflectedType; }
}
/// <inheritdoc/>
public override MethodAttributes Attributes {
get { return methodInfo.Attributes; }
}
/// <inheritdoc/>
public override bool ContainsGenericParameters {
get { return methodInfo.ContainsGenericParameters; }
}
/// <inheritdoc/>
public override bool IsGenericMethod {
get { return methodInfo.IsGenericMethod; }
}
/// <inheritdoc/>
public override bool IsGenericMethodDefinition {
get { return methodInfo.IsGenericMethodDefinition; }
}
/// <inheritdoc/>
public override RuntimeMethodHandle MethodHandle {
get { return methodInfo.MethodHandle; }
}
DebugType IDebugMemberInfo.MemberType {
get { return ((IDebugMemberInfo)methodInfo).MemberType; }
}
/// <inheritdoc/>
public override object[] GetCustomAttributes(bool inherit)
{
return methodInfo.GetCustomAttributes(inherit);
}
/// <inheritdoc/>
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return methodInfo.GetCustomAttributes(attributeType, inherit);
}
/// <inheritdoc/>
public override bool IsDefined(Type attributeType, bool inherit)
{
return methodInfo.IsDefined(attributeType, inherit);
}
/// <inheritdoc/>
public override MethodImplAttributes GetMethodImplementationFlags()
{
return methodInfo.GetMethodImplementationFlags();
}
/// <inheritdoc/>
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
return methodInfo.Invoke(null, invokeAttr, binder, parameters, culture);
}
/// <inheritdoc/>
public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
return methodInfo.Invoke(null, invokeAttr, binder, parameters, culture);
}
/// <inheritdoc/>
public override ParameterInfo[] GetParameters()
{
return methodInfo.GetParameters();
}
/// <inheritdoc/>
public override string ToString()
{
return methodInfo.ToString();
}
}
}

131
Debugger/Debugger.Core/MetaData/DebugFieldInfo.cs

@ -0,0 +1,131 @@ @@ -0,0 +1,131 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Globalization;
using System.Reflection;
using Debugger.Interop.MetaData;
using Mono.Cecil.Signatures;
namespace Debugger.MetaData
{
public class DebugFieldInfo : System.Reflection.FieldInfo, IDebugMemberInfo
{
DebugType declaringType;
FieldProps fieldProps;
internal DebugFieldInfo(DebugType declaringType, FieldProps fieldProps)
{
this.declaringType = declaringType;
this.fieldProps = fieldProps;
}
/// <inheritdoc/>
public override Type DeclaringType {
get { return declaringType; }
}
internal FieldProps FieldProps {
get { return fieldProps; }
}
/// <summary> The AppDomain in which this member is declared </summary>
public AppDomain AppDomain {
get { return declaringType.AppDomain; }
}
/// <summary> The Process in which this member is declared </summary>
public Process Process {
get { return declaringType.Process; }
}
/// <summary> The Module in which this member is declared </summary>
public Debugger.Module DebugModule {
get { return declaringType.DebugModule; }
}
/// <inheritdoc/>
public override int MetadataToken {
get { return (int)fieldProps.Token; }
}
/// <inheritdoc/>
public override System.Reflection.Module Module {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override string Name {
get { return fieldProps.Name; }
}
/// <inheritdoc/>
public override Type ReflectedType {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override bool IsDefined(Type attributeType, bool inherit)
{
return DebugType.IsDefined(this, inherit, attributeType);
}
/// <inheritdoc/>
public override FieldAttributes Attributes {
get { return (FieldAttributes)fieldProps.Flags; }
}
/// <inheritdoc/>
public override RuntimeFieldHandle FieldHandle {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override Type FieldType {
get {
SignatureReader sigReader = new SignatureReader(fieldProps.SigBlob.GetData());
FieldSig fieldSig = sigReader.GetFieldSig(0);
return DebugType.CreateFromSignature(this.DebugModule, fieldSig.Type, declaringType);
}
}
// public virtual Type[] GetOptionalCustomModifiers();
// public virtual object GetRawConstantValue();
// public virtual Type[] GetRequiredCustomModifiers();
/// <inheritdoc/>
public override object GetValue(object obj)
{
return Value.GetFieldValue((Value)obj, this);
}
/// <inheritdoc/>
public override void SetValue(object obj, object value, System.Reflection.BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
Value.SetFieldValue((Value)obj, this, (Value)value);
}
/// <inheritdoc/>
public override string ToString()
{
return this.FieldType + " " + this.Name;
}
DebugType IDebugMemberInfo.MemberType {
get { return (DebugType)this.FieldType; }
}
}
}

61
Debugger/Debugger.Core/MetaData/DebugLocalVariableInfo.cs

@ -0,0 +1,61 @@ @@ -0,0 +1,61 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
namespace Debugger.MetaData
{
public class DebugLocalVariableInfo: System.Reflection.LocalVariableInfo
{
ValueGetter getter;
int localIndex;
DebugType localType;
/// <inheritdoc/>
public override int LocalIndex {
get { return localIndex; }
}
/// <inheritdoc/>
public override Type LocalType {
get { return localType; }
}
/// <inheritdoc/>
public override bool IsPinned {
get { throw new NotSupportedException(); }
}
public string Name { get; internal set; }
/// <summary> IL offset of the start of the variable scope (inclusive) </summary>
public int StartOffset { get; private set; }
/// <summary> IL offset of the end of the variable scope (exclusive) </summary>
public int EndOffset { get; private set; }
public bool IsThis { get; internal set; }
public bool IsCaptured { get; internal set; }
public DebugLocalVariableInfo(string name, int localIndex, int startOffset, int endOffset, DebugType localType, ValueGetter getter)
{
this.Name = name;
this.localIndex = localIndex;
this.StartOffset = startOffset;
this.EndOffset = endOffset;
this.localType = localType;
this.getter = getter;
}
public Value GetValue(StackFrame context)
{
return getter(context);
}
/// <inheritdoc/>
public override string ToString()
{
string msg = this.LocalType + " " + this.Name;
if (IsCaptured)
msg += " (captured)";
return msg;
}
}
}

664
Debugger/Debugger.Core/MetaData/DebugMethodInfo.cs

@ -0,0 +1,664 @@ @@ -0,0 +1,664 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Debugger.Interop.CorDebug;
using Debugger.Interop.CorSym;
using Debugger.Interop.MetaData;
using Mono.Cecil.Signatures;
namespace Debugger.MetaData
{
public class DebugMethodInfo: System.Reflection.MethodInfo, IDebugMemberInfo, IOverloadable
{
DebugType declaringType;
MethodProps methodProps;
internal DebugMethodInfo(DebugType declaringType, MethodProps methodProps)
{
this.declaringType = declaringType;
this.methodProps = methodProps;
}
/// <inheritdoc/>
public override Type DeclaringType {
get { return declaringType; }
}
/// <summary> The AppDomain in which this member is declared </summary>
public AppDomain AppDomain {
get { return declaringType.AppDomain; }
}
/// <summary> The Process in which this member is declared </summary>
public Process Process {
get { return declaringType.Process; }
}
/// <summary> The Module in which this member is declared </summary>
public Debugger.Module DebugModule {
get { return declaringType.DebugModule; }
}
/// <inheritdoc/>
public override int MetadataToken {
get { return (int)methodProps.Token; }
}
/// <inheritdoc/>
public override System.Reflection.Module Module {
get { throw new NotSupportedException(); }
}
/// <summary> Name including the declaring type, return type and parameters </summary>
public string FullName {
get {
StringBuilder sb = new StringBuilder();
if (this.IsStatic) {
sb.Append("static ");
}
if (this.ReturnType != null) {
sb.Append(this.ReturnType.Name);
sb.Append(" ");
} else {
sb.Append("void ");
}
sb.Append(this.DeclaringType.FullName);
sb.Append(".");
sb.Append(this.Name);
sb.Append("(");
bool first = true;
foreach(DebugParameterInfo p in GetParameters()) {
if (!first)
sb.Append(", ");
first = false;
sb.Append(p.ParameterType.Name);
sb.Append(" ");
sb.Append(p.Name);
}
sb.Append(")");
return sb.ToString();
}
}
/// <inheritdoc/>
public override string Name {
get { return methodProps.Name; }
}
/// <inheritdoc/>
public override Type ReflectedType {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override bool IsDefined(Type attributeType, bool inherit)
{
return DebugType.IsDefined(this, inherit, attributeType);
}
// public virtual Type[] GetGenericArguments();
// public virtual MethodBody GetMethodBody();
/// <inheritdoc/>
public override MethodImplAttributes GetMethodImplementationFlags()
{
return (MethodImplAttributes)methodProps.ImplFlags;
}
/// <inheritdoc/>
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
List<Value> args = new List<Value>();
foreach(object arg in parameters) {
args.Add((Value)arg);
}
if (this.IsSpecialName && this.Name == ".ctor") {
if (obj != null)
throw new GetValueException("'obj' must be null for constructor call");
return Eval.NewObject(this, args.ToArray());
} else {
return Eval.InvokeMethod(this, (Value)obj, args.ToArray());
}
}
/// <inheritdoc/>
public override MethodAttributes Attributes {
get { return (MethodAttributes)methodProps.Flags; }
}
// public virtual CallingConventions CallingConvention { get; }
/// <inheritdoc/>
public override bool ContainsGenericParameters {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override bool IsGenericMethod {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override bool IsGenericMethodDefinition {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override RuntimeMethodHandle MethodHandle {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override MethodInfo GetBaseDefinition()
{
throw new NotSupportedException();
}
// public override Type[] GetGenericArguments();
// public virtual MethodInfo GetGenericMethodDefinition();
// public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments);
// public override bool ContainsGenericParameters { get; }
/// <inheritdoc/>
public override Type ReturnType {
get {
if (this.MethodDefSig.RetType.Void) return null;
return DebugType.CreateFromSignature(this.DebugModule, this.MethodDefSig.RetType.Type, declaringType);
}
}
/// <inheritdoc/>
public override ParameterInfo ReturnParameter {
get {
if (this.MethodDefSig.RetType.Void) return null;
return new DebugParameterInfo(this, string.Empty, this.ReturnType, -1, delegate { throw new NotSupportedException(); });
}
}
/// <inheritdoc/>
public override ICustomAttributeProvider ReturnTypeCustomAttributes {
get { throw new NotSupportedException(); }
}
MethodDefSig methodDefSig;
MethodDefSig MethodDefSig {
get {
if (methodDefSig == null) {
SignatureReader sigReader = new SignatureReader(methodProps.SigBlob.GetData());
methodDefSig = sigReader.GetMethodDefSig(0);
}
return methodDefSig;
}
}
/// <summary> Gets the number of paramters of this method </summary>
public int ParameterCount {
get { return this.MethodDefSig.ParamCount; }
}
ParameterInfo[] parameters;
public DebugParameterInfo GetParameter(string name)
{
foreach(DebugParameterInfo par in GetParameters()) {
if (par.Name == name)
return par;
}
return null;
}
/// <inheritdoc/>
public override ParameterInfo[] GetParameters()
{
if (parameters == null) {
parameters = new ParameterInfo[this.MethodDefSig.ParamCount];
for(int i = 0; i < parameters.Length; i++) {
string name;
try {
// index = 0 is return parameter
name = this.DebugModule.MetaData.GetParamPropsForMethodIndex((uint)this.MetadataToken, (uint)i + 1).Name;
} catch {
name = String.Empty;
}
int iCopy = i;
parameters[i] =
new DebugParameterInfo(
this,
name,
DebugType.CreateFromSignature(this.DebugModule, this.MethodDefSig.Parameters[i].Type, declaringType),
i,
delegate (StackFrame context) { return context.GetArgumentValue(iCopy); }
);
}
}
return parameters;
}
internal ICorDebugFunction CorFunction {
get {
return this.DebugModule.CorModule.GetFunctionFromToken((uint)this.MetadataToken);
}
}
/// <summary> Gets value indicating whether this method should be stepped over
/// accoring to current options </summary>
public bool StepOver {
get {
Options opt = this.Process.Options;
if (opt.StepOverNoSymbols) {
if (this.SymMethod == null) return true;
}
if (opt.StepOverDebuggerAttributes) {
if (this.IsNonUserCode) return true;
}
if (opt.StepOverAllProperties) {
if (this.IsPropertyAccessor) return true;
}
if (opt.StepOverSingleLineProperties) {
if (this.IsPropertyAccessor && this.IsSingleLine) return true;
}
if (opt.StepOverFieldAccessProperties) {
if (this.IsPropertyAccessor && this.BackingFieldToken != 0) return true;
}
return false;
}
}
internal bool IsPropertyAccessor { get; set; }
uint backingFieldToken;
/// <summary>
/// Backing field that can be used to obtain the same value as by calling this method.
/// </summary>
[Tests.Ignore]
public uint BackingFieldToken {
get {
LoadBackingFieldToken();
return backingFieldToken;
}
}
/// <summary>
/// Backing field that can be used to obtain the same value as by calling this method.
/// It works only for fields defined in the class
/// </summary>
public DebugFieldInfo BackingField {
get {
uint token = this.BackingFieldToken;
if (token == 0) return null;
// The token can be a field in different class (static or instance in base class) - so it might not be found in the next call
MemberInfo member;
if (!declaringType.TryGetMember(token, out member)) return null;
return (DebugFieldInfo)member;
}
}
bool loadBackingFieldTokenCalled;
/// <summary> Is this method in form 'return this.field;'? </summary>
void LoadBackingFieldToken()
{
if (loadBackingFieldTokenCalled) return;
loadBackingFieldTokenCalled = true;
backingFieldToken = 0;
if (this.ParameterCount != 0) return;
ICorDebugCode corCode;
try {
corCode = this.CorFunction.GetILCode();
} catch (COMException) {
return;
}
if (corCode == null || corCode.IsIL() == 0 || corCode.GetSize() > 12) return;
List<byte> code = new List<byte>(corCode.GetCode());
uint token = 0;
bool success =
(Read(code, 0x00) || true) && // nop || nothing
(Read(code, 0x02, 0x7B) || Read(code, 0x7E)) && // ldarg.0; ldfld || ldsfld
ReadToken(code, ref token) && // <field token>
(Read(code, 0x0A, 0x2B, 0x00, 0x06) || true) && // stloc.0; br.s; offset+00; ldloc.0 || nothing
Read(code, 0x2A); // ret
if (!success) return;
if (this.Process.Options.Verbose) {
this.Process.TraceMessage(string.Format("Found backing field for {0}", this.FullName));
}
backingFieldToken = token;
}
// Read expected sequence of bytes
static bool Read(List<byte> code, params byte[] expected)
{
if (code.Count < expected.Length)
return false;
for(int i = 0; i < expected.Length; i++) {
if (code[i] != expected[i])
return false;
}
code.RemoveRange(0, expected.Length);
return true;
}
// Read field token
static bool ReadToken(List<byte> code, ref uint token)
{
if (code.Count < 4)
return false;
if (code[3] != 0x04) // field token
return false;
token = ((uint)code[0]) + ((uint)code[1] << 8) + ((uint)code[2] << 16) + ((uint)code[3] << 24);
code.RemoveRange(0, 4);
return true;
}
bool? isSingleLine;
bool IsSingleLine {
get {
// Note symbols might get loaded manually later by the user
ISymUnmanagedMethod symMethod = this.SymMethod;
if (symMethod == null) return false; // No symbols - can not determine
if (isSingleLine.HasValue) return isSingleLine.Value;
List<SequencePoint> seqPoints = new List<SequencePoint>(symMethod.GetSequencePoints());
seqPoints.Sort();
// Remove initial "{"
if (seqPoints.Count > 0 &&
seqPoints[0].Line == seqPoints[0].EndLine &&
seqPoints[0].EndColumn - seqPoints[0].Column <= 1) {
seqPoints.RemoveAt(0);
}
// Remove last "}"
int listIndex = seqPoints.Count - 1;
if (seqPoints.Count > 0 &&
seqPoints[listIndex].Line == seqPoints[listIndex].EndLine &&
seqPoints[listIndex].EndColumn - seqPoints[listIndex].Column <= 1) {
seqPoints.RemoveAt(listIndex);
}
// Is single line
isSingleLine = seqPoints.Count == 0 || seqPoints[0].Line == seqPoints[seqPoints.Count - 1].EndLine;
return isSingleLine.Value;
}
}
bool? isNonUserCode;
public bool IsNonUserCode {
get {
if (isNonUserCode.HasValue) return isNonUserCode.Value;
isNonUserCode =
// Look on the method
DebugType.IsDefined(
this,
false,
typeof(System.Diagnostics.DebuggerStepThroughAttribute),
typeof(System.Diagnostics.DebuggerNonUserCodeAttribute),
typeof(System.Diagnostics.DebuggerHiddenAttribute))
||
// Look on the type
DebugType.IsDefined(
declaringType,
false,
typeof(System.Diagnostics.DebuggerStepThroughAttribute),
typeof(System.Diagnostics.DebuggerNonUserCodeAttribute),
typeof(System.Diagnostics.DebuggerHiddenAttribute));
return isNonUserCode.Value;
}
}
internal void MarkAsNonUserCode()
{
((ICorDebugFunction2)this.CorFunction).SetJMCStatus(0 /* false */);
if (this.Process.Options.Verbose) {
this.Process.TraceMessage("Funciton {0} marked as non-user code", this.FullName);
}
}
internal ISymUnmanagedMethod SymMethod {
get {
if (this.DebugModule.SymReader == null) return null;
try {
return this.DebugModule.SymReader.GetMethod((uint)this.MetadataToken);
} catch {
return null;
}
}
}
public DebugLocalVariableInfo GetLocalVariable(int offset, string name)
{
foreach(DebugLocalVariableInfo loc in GetLocalVariables(offset)) {
if (loc.Name == name)
return loc;
}
return null;
}
[Debugger.Tests.Ignore]
public DebugLocalVariableInfo GetLocalVariableThis()
{
foreach(DebugLocalVariableInfo loc in GetLocalVariables()) {
if (loc.IsThis)
return loc;
}
return null;
}
/// <summary> Get local variables valid at the given IL offset </summary>
public IEnumerable<DebugLocalVariableInfo> GetLocalVariables(int offset)
{
foreach (DebugLocalVariableInfo varInfo in GetLocalVariables()) {
if (varInfo.StartOffset <= offset && offset < varInfo.EndOffset) {
yield return varInfo;
}
}
}
List<DebugLocalVariableInfo> localVariables;
public List<DebugLocalVariableInfo> GetLocalVariables()
{
if (localVariables != null) return localVariables;
// Generated constructor may not have any symbols
if (this.SymMethod == null)
return new List<DebugLocalVariableInfo>();
localVariables = GetLocalVariablesInScope(this.SymMethod.GetRootScope());
if (declaringType.IsDisplayClass || declaringType.IsYieldEnumerator) {
// Get display class from self
AddCapturedLocalVariables(
localVariables,
0, int.MaxValue,
delegate(StackFrame context) {
return context.GetThisValue();
},
declaringType
);
// Get dispaly classes from fields
foreach(DebugFieldInfo fieldInfo in this.DeclaringType.GetFields()) {
DebugFieldInfo fieldInfoCopy = fieldInfo;
if (fieldInfo.Name.StartsWith("CS$")) {
AddCapturedLocalVariables(
localVariables,
0, int.MaxValue,
delegate(StackFrame context) {
return context.GetThisValue().GetFieldValue(fieldInfoCopy);
},
(DebugType)fieldInfo.FieldType
);
}
}
} else {
// Add this
if (!this.IsStatic) {
DebugLocalVariableInfo thisVar = new DebugLocalVariableInfo(
"this",
-1,
0, int.MaxValue,
declaringType,
delegate(StackFrame context) {
return context.GetThisValue();
}
);
thisVar.IsThis = true;
localVariables.Add(thisVar);
}
}
return localVariables;
}
static void AddCapturedLocalVariables(List<DebugLocalVariableInfo> vars, int scopeStartOffset, int scopeEndOffset, ValueGetter getCaptureClass, DebugType captureClassType)
{
if (captureClassType.IsDisplayClass || captureClassType.IsYieldEnumerator) {
foreach(DebugFieldInfo fieldInfo in captureClassType.GetFields()) {
DebugFieldInfo fieldInfoCopy = fieldInfo;
if (fieldInfo.Name.StartsWith("CS$")) continue; // Ignore
DebugLocalVariableInfo locVar = new DebugLocalVariableInfo(
fieldInfo.Name,
-1,
scopeStartOffset,
scopeEndOffset,
(DebugType)fieldInfo.FieldType,
delegate(StackFrame context) {
return getCaptureClass(context).GetFieldValue(fieldInfoCopy);
}
);
locVar.IsCaptured = true;
if (locVar.Name.StartsWith("<>")) {
bool hasThis = false;
foreach(DebugLocalVariableInfo l in vars) {
if (l.IsThis) {
hasThis = true;
break;
}
}
if (!hasThis && locVar.Name.EndsWith("__this")) {
locVar.Name = "this";
locVar.IsThis = true;
} else {
continue; // Ignore
}
}
if (locVar.Name.StartsWith("<")) {
int endIndex = locVar.Name.IndexOf('>');
if (endIndex == -1) continue; // Ignore
locVar.Name = fieldInfo.Name.Substring(1, endIndex - 1);
}
vars.Add(locVar);
}
}
}
List<DebugLocalVariableInfo> GetLocalVariablesInScope(ISymUnmanagedScope symScope)
{
List<DebugLocalVariableInfo> vars = new List<DebugLocalVariableInfo>();
foreach (ISymUnmanagedVariable symVar in symScope.GetLocals()) {
ISymUnmanagedVariable symVarCopy = symVar;
int start;
SignatureReader sigReader = new SignatureReader(symVar.GetSignature());
LocalVarSig.LocalVariable locVarSig = sigReader.ReadLocalVariable(sigReader.Blob, 0, out start);
DebugType locVarType = DebugType.CreateFromSignature(this.DebugModule, locVarSig.Type, declaringType);
// Compiler generated?
// NB: Display class does not have the compiler-generated flag
if ((symVar.GetAttributes() & 1) == 1 || symVar.GetName().StartsWith("CS$")) {
// Get display class from local variable
if (locVarType.IsDisplayClass) {
AddCapturedLocalVariables(
vars,
(int)symScope.GetStartOffset(),
(int)symScope.GetEndOffset(),
delegate(StackFrame context) {
return GetLocalVariableValue(context, symVarCopy);
},
locVarType
);
}
} else {
DebugLocalVariableInfo locVar = new DebugLocalVariableInfo(
symVar.GetName(),
(int)symVar.GetAddressField1(),
// symVar also has Get*Offset methods, but the are not implemented
(int)symScope.GetStartOffset(),
(int)symScope.GetEndOffset(),
locVarType,
delegate(StackFrame context) {
return GetLocalVariableValue(context, symVarCopy);
}
);
vars.Add(locVar);
}
}
foreach(ISymUnmanagedScope childScope in symScope.GetChildren()) {
vars.AddRange(GetLocalVariablesInScope(childScope));
}
return vars;
}
static Value GetLocalVariableValue(StackFrame context, ISymUnmanagedVariable symVar)
{
ICorDebugValue corVal;
try {
corVal = context.CorILFrame.GetLocalVariable((uint)symVar.GetAddressField1());
} catch (COMException e) {
if ((uint)e.ErrorCode == 0x80131304) throw new GetValueException("Unavailable in optimized code");
throw;
}
return new Value(context.AppDomain, corVal);
}
/// <inheritdoc/>
public override string ToString()
{
return this.FullName;
}
IntPtr IOverloadable.GetSignarture()
{
return methodProps.SigBlob.Adress;
}
DebugType IDebugMemberInfo.MemberType {
get { return (DebugType)this.ReturnType; }
}
}
}

67
Debugger/Debugger.Core/MetaData/DebugParameterInfo.cs

@ -0,0 +1,67 @@ @@ -0,0 +1,67 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Reflection;
namespace Debugger.MetaData
{
public class DebugParameterInfo : System.Reflection.ParameterInfo
{
ValueGetter getter;
MemberInfo member;
string name;
Type parameterType;
int position;
/// <inheritdoc/>
public override MemberInfo Member {
get { return member; }
}
/// <inheritdoc/>
public override string Name {
get { return name; }
}
/// <inheritdoc/>
public override Type ParameterType {
get { return parameterType; }
}
/// <inheritdoc/>
public override int Position {
get { return position; }
}
public DebugParameterInfo(MemberInfo member, string name, Type parameterType, int position, ValueGetter getter)
{
this.member = member;
this.name = name;
this.parameterType = parameterType;
this.position = position;
this.getter = getter;
}
public Value GetValue(StackFrame context)
{
return getter(context);
}
// public virtual ParameterAttributes Attributes { get; }
// public virtual object DefaultValue { get; }
// public virtual object RawDefaultValue { get; }
//
// public virtual object[] GetCustomAttributes(bool inherit);
// public virtual object[] GetCustomAttributes(Type attributeType, bool inherit);
// public virtual Type[] GetOptionalCustomModifiers();
// public virtual Type[] GetRequiredCustomModifiers();
// public virtual bool IsDefined(Type attributeType, bool inherit);
/// <inheritdoc/>
public override string ToString()
{
return this.ParameterType + " " + this.Name;
}
}
}

244
Debugger/Debugger.Core/MetaData/DebugPropertyInfo.cs

@ -0,0 +1,244 @@ @@ -0,0 +1,244 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace Debugger.MetaData
{
public class DebugPropertyInfo : System.Reflection.PropertyInfo, IDebugMemberInfo, IOverloadable
{
DebugType declaringType;
string name;
MethodInfo getMethod;
MethodInfo setMethod;
internal DebugPropertyInfo(DebugType declaringType, string name, MethodInfo getMethod, MethodInfo setMethod)
{
if (getMethod == null && setMethod == null) throw new ArgumentNullException("Both getter and setter can not be null.");
this.declaringType = declaringType;
this.name = name;
this.getMethod = getMethod;
this.setMethod = setMethod;
}
/// <inheritdoc/>
public override Type DeclaringType {
get { return declaringType; }
}
/// <summary> The AppDomain in which this member is declared </summary>
public AppDomain AppDomain {
get { return declaringType.AppDomain; }
}
/// <summary> The Process in which this member is declared </summary>
public Process Process {
get { return declaringType.Process; }
}
/// <summary> The Module in which this member is declared </summary>
public Debugger.Module DebugModule {
get { return declaringType.DebugModule; }
}
/// <inheritdoc/>
public override int MetadataToken {
get { return 0; }
}
/// <inheritdoc/>
public override System.Reflection.Module Module {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override string Name {
get { return name; }
}
/// <summary> Name including the declaring type, return type and parameters </summary>
public string FullName {
get {
StringBuilder sb = new StringBuilder();
if (this.IsStatic) {
sb.Append("static ");
}
sb.Append(this.PropertyType.Name);
sb.Append(" ");
sb.Append(this.DeclaringType.FullName);
sb.Append(".");
sb.Append(this.Name);
if (GetIndexParameters().Length > 0) {
sb.Append("[");
bool first = true;
foreach(DebugParameterInfo p in GetIndexParameters()) {
if (!first)
sb.Append(", ");
first = false;
sb.Append(p.ParameterType.Name);
sb.Append(" ");
sb.Append(p.Name);
}
sb.Append("]");
}
return sb.ToString();
}
}
/// <inheritdoc/>
public override Type ReflectedType {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override bool IsDefined(Type attributeType, bool inherit)
{
return DebugType.IsDefined(this, inherit, attributeType);
}
/// <inheritdoc/>
public override PropertyAttributes Attributes {
get { throw new NotSupportedException(); }
}
/// <inheritdoc/>
public override bool CanRead {
get { return getMethod != null; }
}
/// <inheritdoc/>
public override bool CanWrite {
get { return setMethod != null; }
}
/// <inheritdoc/>
public override Type PropertyType {
get {
if (getMethod != null) {
return getMethod.ReturnType;
} else {
return setMethod.GetParameters()[setMethod.GetParameters().Length - 1].ParameterType;
}
}
}
/// <inheritdoc/>
public override MethodInfo[] GetAccessors(bool nonPublic)
{
throw new NotSupportedException();
}
// public virtual object GetConstantValue();
/// <inheritdoc/>
public override MethodInfo GetGetMethod(bool nonPublic)
{
return getMethod;
}
/// <inheritdoc/>
public override ParameterInfo[] GetIndexParameters()
{
if (GetGetMethod() != null) {
return GetGetMethod().GetParameters();
}
if (GetSetMethod() != null) {
List<ParameterInfo> pars = new List<ParameterInfo>();
pars.AddRange(GetSetMethod().GetParameters());
pars.RemoveAt(pars.Count - 1);
return pars.ToArray();
}
return null;
}
// public virtual Type[] GetOptionalCustomModifiers();
// public virtual object GetRawConstantValue();
// public virtual Type[] GetRequiredCustomModifiers();
/// <inheritdoc/>
public override MethodInfo GetSetMethod(bool nonPublic)
{
return setMethod;
}
/// <inheritdoc/>
public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
List<Value> args = new List<Value>();
foreach(object arg in index) {
args.Add((Value)arg);
}
return Value.GetPropertyValue((Value)obj, this, args.ToArray());
}
/// <inheritdoc/>
public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
List<Value> args = new List<Value>();
foreach(object arg in index) {
args.Add((Value)arg);
}
Value.SetPropertyValue((Value)obj, this, args.ToArray(), (Value)value);
}
public bool IsPublic {
get { return (getMethod ?? setMethod).IsPublic; }
}
public bool IsAssembly {
get { return (getMethod ?? setMethod).IsAssembly; }
}
public bool IsFamily {
get { return (getMethod ?? setMethod).IsFamily; }
}
public bool IsPrivate {
get { return (getMethod ?? setMethod).IsPrivate; }
}
public bool IsStatic {
get { return (getMethod ?? setMethod).IsStatic; }
}
DebugType IDebugMemberInfo.MemberType {
get { return (DebugType)this.PropertyType; }
}
ParameterInfo[] IOverloadable.GetParameters()
{
return GetIndexParameters();
}
IntPtr IOverloadable.GetSignarture()
{
return ((IOverloadable)(getMethod ?? setMethod)).GetSignarture();
}
/// <inheritdoc/>
public override string ToString()
{
return this.FullName;
}
}
}

1377
Debugger/Debugger.Core/MetaData/DebugType.cs

File diff suppressed because it is too large Load Diff

21
Debugger/Debugger.Core/MetaData/IDebugMemberInfo.cs

@ -0,0 +1,21 @@ @@ -0,0 +1,21 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
namespace Debugger.MetaData
{
public interface IDebugMemberInfo
{
Type DeclaringType { get; }
Module DebugModule { get; }
string Name { get; }
int MetadataToken { get; }
bool IsStatic { get; }
bool IsPublic { get; }
bool IsAssembly { get; }
bool IsFamily { get; }
bool IsPrivate { get; }
DebugType MemberType { get; }
}
}

14
Debugger/Debugger.Core/MetaData/IOverloadable.cs

@ -0,0 +1,14 @@ @@ -0,0 +1,14 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Reflection;
namespace Debugger.MetaData
{
interface IOverloadable
{
ParameterInfo[] GetParameters();
IntPtr GetSignarture();
}
}

408
Debugger/Debugger.Core/Module.cs

@ -0,0 +1,408 @@ @@ -0,0 +1,408 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Debugger.Interop;
using Debugger.Interop.CorDebug;
using Debugger.Interop.CorSym;
using Debugger.Interop.MetaData;
using Debugger.MetaData;
namespace Debugger
{
public class Module: DebuggerObject, IDisposable
{
AppDomain appDomain;
Process process;
bool unloaded = false;
string name;
string fullPath = string.Empty;
int orderOfLoading = 0;
ICorDebugModule corModule;
ISymUnmanagedReader symReader;
MetaDataImport metaData;
internal Dictionary<string, DebugType> LoadedDebugTypes = new Dictionary<string, DebugType>();
/// <summary>
/// Occurs when symbols are loaded or unloaded (for memory modules)
/// </summary>
public event EventHandler<ModuleEventArgs> SymbolsUpdated;
public AppDomain AppDomain {
get { return appDomain; }
}
public Process Process {
get { return process; }
}
NDebugger Debugger {
get { return this.AppDomain.Process.Debugger; }
}
[Debugger.Tests.Ignore]
public MetaDataImport MetaData {
get {
return metaData;
}
}
public bool Unloaded {
get {
return unloaded;
}
}
[Debugger.Tests.Ignore]
public ISymUnmanagedReader SymReader {
get {
return symReader;
}
}
[Debugger.Tests.Ignore]
public ISymUnmanagedDocument[] SymDocuments {
get {
ISymUnmanagedDocument[] docs;
uint maxCount = 2;
uint fetched;
do {
maxCount *= 8;
docs = new ISymUnmanagedDocument[maxCount];
symReader.GetDocuments(maxCount, out fetched, docs);
} while (fetched == maxCount);
Array.Resize(ref docs, (int)fetched);
return docs;
}
}
[Debugger.Tests.Ignore]
public ICorDebugModule CorModule {
get { return corModule; }
}
[Debugger.Tests.Ignore]
public ICorDebugModule2 CorModule2 {
get { return (ICorDebugModule2)corModule; }
}
[Debugger.Tests.Ignore]
public ulong BaseAdress {
get {
return this.CorModule.GetBaseAddress();
}
}
public bool IsDynamic {
get {
return this.CorModule.IsDynamic() == 1;
}
}
public bool IsInMemory {
get {
return this.CorModule.IsInMemory() == 1;
}
}
internal uint AppDomainID {
get {
return this.CorModule.GetAssembly().GetAppDomain().GetID();
}
}
public string Name {
get {
return name;
}
}
[Debugger.Tests.Ignore]
public string FullPath {
get {
return fullPath;
}
}
public bool HasSymbols {
get {
return symReader != null;
}
}
public int OrderOfLoading {
get {
return orderOfLoading;
}
set {
orderOfLoading = value;
}
}
[Debugger.Tests.Ignore]
public CorDebugJITCompilerFlags JITCompilerFlags
{
get
{
uint retval = ((ICorDebugModule2)corModule).GetJITCompilerFlags();
return (CorDebugJITCompilerFlags)retval;
}
set
{
// ICorDebugModule2.SetJITCompilerFlags can return successful HRESULTS other than S_OK.
// Since we have asked the COMInterop layer to preservesig, we need to marshal any failing HRESULTS.
((ICorDebugModule2)corModule).SetJITCompilerFlags((uint)value);
}
}
/// <summary> Returns all non-generic types defined in the module </summary>
/// <remarks> Generic types can not be returned, because we do not know how to instanciate them </remarks>
public List<DebugType> GetDefinedTypes()
{
List<DebugType> types = new List<DebugType>();
foreach(TypeDefProps typeDef in this.MetaData.EnumTypeDefProps()) {
if (this.MetaData.EnumGenericParams(typeDef.Token).Length == 0) {
types.Add(DebugType.CreateFromTypeDefOrRef(this, null, typeDef.Token, null));
}
}
return types;
}
/// <summary> Get names of all generic and non-generic types defined in this module </summary>
public List<string> GetNamesOfDefinedTypes()
{
List<string> names = new List<string>();
foreach(TypeDefProps typeProps in this.MetaData.EnumTypeDefProps()) {
names.Add(typeProps.Name);
}
return names;
}
internal Module(AppDomain appDomain, ICorDebugModule corModule)
{
this.appDomain = appDomain;
this.process = appDomain.Process;
this.corModule = corModule;
SetJITCompilerFlags();
metaData = new MetaDataImport(corModule);
if (IsDynamic || IsInMemory) {
name = corModule.GetName();
} else {
fullPath = corModule.GetName();
name = System.IO.Path.GetFileName(FullPath);
}
LoadSymbolsFromDisk(process.Options.SymbolsSearchPaths);
ResetJustMyCodeStatus();
}
public void UnloadSymbols()
{
if (symReader != null) {
// The interface is not always supported, I did not manage to reproduce it, but the
// last callbacks in the user's log were UnloadClass and UnloadModule so I guess
// it has something to do with dynamic modules.
if (symReader is ISymUnmanagedDispose) {
((ISymUnmanagedDispose)symReader).Destroy();
}
symReader = null;
}
}
/// <summary>
/// Load symblos for on-disk module
/// </summary>
public void LoadSymbolsFromDisk(string[] searchPath)
{
if (!IsDynamic && !IsInMemory) {
if (symReader == null) {
symReader = metaData.GetSymReader(fullPath, string.Join("; ", searchPath ?? new string[0]));
if (symReader != null) {
process.TraceMessage("Loaded symbols from disk for " + this.Name);
OnSymbolsUpdated();
}
}
}
}
/// <summary>
/// Load symbols for in-memory module
/// </summary>
public void LoadSymbolsFromMemory(IStream pSymbolStream)
{
if (this.IsInMemory) {
UnloadSymbols();
symReader = metaData.GetSymReader(pSymbolStream);
if (symReader != null) {
process.TraceMessage("Loaded symbols from memory for " + this.Name);
} else {
process.TraceMessage("Failed to load symbols from memory");
}
OnSymbolsUpdated();
}
}
/// <summary>
/// Load symbols for dynamic module
/// (as of .NET 4.0)
/// </summary>
public void LoadSymbolsDynamic()
{
if (this.CorModule is ICorDebugModule3 && this.IsDynamic) {
Guid guid = new Guid(0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 70);
try {
symReader = (ISymUnmanagedReader)((ICorDebugModule3)this.CorModule).CreateReaderForInMemorySymbols(guid);
} catch (COMException e) {
// 0x80131C3B The application did not supply symbols when it loaded or created this module, or they are not yet available.
if ((uint)e.ErrorCode == 0x80131C3B) {
process.TraceMessage("Failed to load dynamic symbols for " + this.Name);
return;
}
throw;
}
TrackedComObjects.Track(symReader);
process.TraceMessage("Loaded dynamic symbols for " + this.Name);
OnSymbolsUpdated();
}
}
void OnSymbolsUpdated()
{
SetBreakpoints();
ResetJustMyCodeStatus();
if (SymbolsUpdated != null) {
SymbolsUpdated(this, new ModuleEventArgs(this));
}
}
void SetBreakpoints()
{
if (this.HasSymbols) {
// This is in case that the client modifies the collection as a response to set breakpoint
// NB: If client adds new breakpoint, it will be set directly as a result of his call, not here (because module is already loaded)
List<Breakpoint> collection = new List<Breakpoint>();
collection.AddRange(this.Debugger.Breakpoints);
foreach (Breakpoint b in collection) {
b.SetBreakpoint(this);
}
}
}
void SetJITCompilerFlags()
{
if (Process.DebugMode != DebugModeFlag.Default) {
// translate DebugModeFlags to JITCompilerFlags
CorDebugJITCompilerFlags jcf = MapDebugModeToJITCompilerFlags(Process.DebugMode);
try
{
this.JITCompilerFlags = jcf;
// Flags may succeed but not set all bits, so requery.
CorDebugJITCompilerFlags jcfActual = this.JITCompilerFlags;
#if DEBUG
if (jcf != jcfActual)
Console.WriteLine("Couldn't set all flags. Actual flags:" + jcfActual.ToString());
else
Console.WriteLine("Actual flags:" + jcfActual.ToString());
#endif
}
catch (COMException ex)
{
// we'll ignore the error if we cannot set the jit flags
Console.WriteLine(string.Format("Failed to set flags with hr=0x{0:x}", ex.ErrorCode));
}
}
}
/// <summary> Sets all code as being 'my code'. The code will be gradually
/// set to not-user-code as encountered acording to stepping options </summary>
public void ResetJustMyCodeStatus()
{
uint unused = 0;
if (process.Options.StepOverNoSymbols && !this.HasSymbols) {
// Optimization - set the code as non-user right away
this.CorModule2.SetJMCStatus(0, 0, ref unused);
return;
}
try {
this.CorModule2.SetJMCStatus(1, 0, ref unused);
} catch (COMException e) {
// Cannot use JMC on this code (likely wrong JIT settings).
if ((uint)e.ErrorCode == 0x80131323) {
process.TraceMessage("Cannot use JMC on this code. Release build?");
return;
}
throw;
}
}
public void ApplyChanges(byte[] metadata, byte[] il)
{
this.CorModule2.ApplyChanges((uint)metadata.Length, metadata, (uint)il.Length, il);
}
public void Dispose()
{
UnloadSymbols();
unloaded = true;
}
public override string ToString()
{
return string.Format("{0}", this.Name);
}
public static CorDebugJITCompilerFlags MapDebugModeToJITCompilerFlags(DebugModeFlag debugMode)
{
CorDebugJITCompilerFlags jcf;
switch (debugMode)
{
case DebugModeFlag.Optimized:
jcf = CorDebugJITCompilerFlags.CORDEBUG_JIT_DEFAULT; // DEFAULT really means force optimized.
break;
case DebugModeFlag.Debug:
jcf = CorDebugJITCompilerFlags.CORDEBUG_JIT_DISABLE_OPTIMIZATION;
break;
case DebugModeFlag.Enc:
jcf = CorDebugJITCompilerFlags.CORDEBUG_JIT_ENABLE_ENC;
break;
default:
// we don't have mapping from default to "default",
// therefore we'll use DISABLE_OPTIMIZATION.
jcf = CorDebugJITCompilerFlags.CORDEBUG_JIT_DISABLE_OPTIMIZATION;
break;
}
return jcf;
}
}
[Serializable]
public class ModuleEventArgs : ProcessEventArgs
{
Module module;
public Module Module {
get {
return module;
}
}
public ModuleEventArgs(Module module): base(module.Process)
{
this.module = module;
}
}
}

50
Debugger/Debugger.Core/ModuleCollection.cs

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using Debugger.Interop.CorDebug;
namespace Debugger
{
public class ModuleCollection: CollectionWithEvents<Module>
{
public ModuleCollection(NDebugger debugger):base (debugger) {}
int lastAssignedModuleOrderOfLoading = 0;
public Module this[string filename] {
get {
foreach(Module module in this) {
if (module.Name == filename) {
return module;
}
}
throw new DebuggerException("Module \"" + filename + "\" is not in collection");
}
}
internal Module this[ICorDebugModule corModule] {
get {
foreach(Module module in this) {
if (module.CorModule == corModule) {
return module;
}
}
throw new DebuggerException("Module is not in collection");
}
}
protected override void OnAdded(Module module)
{
module.OrderOfLoading = lastAssignedModuleOrderOfLoading;
lastAssignedModuleOrderOfLoading++;
base.OnAdded(module);
}
protected override void OnRemoved(Module module)
{
base.OnRemoved(module);
module.Dispose();
}
}
}

53
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Binary/ImageFormatException.cs

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
//
// ImageFormatException.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Binary {
using System;
public class ImageFormatException : Exception {
internal ImageFormatException () : base()
{
}
internal ImageFormatException (string message) : base(message)
{
}
internal ImageFormatException (string message, params string[] parameters) :
base(string.Format(message, parameters))
{
}
internal ImageFormatException (string message, Exception inner) :
base(message, inner)
{
}
}
}

49
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs

@ -0,0 +1,49 @@ @@ -0,0 +1,49 @@
//
// CodedIndex.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Generated by /CodeGen/cecil-gen.rb do not edit
// Tue Mar 20 16:02:16 +0100 2007
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Metadata {
public enum CodedIndex {
TypeDefOrRef,
HasConstant,
HasCustomAttribute,
HasFieldMarshal,
HasDeclSecurity,
MemberRefParent,
HasSemantics,
MethodDefOrRef,
MemberForwarded,
Implementation,
CustomAttributeType,
ResolutionScope,
TypeOrMethodDef
}
}

73
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs

@ -0,0 +1,73 @@ @@ -0,0 +1,73 @@
//
// ElementType.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Metadata {
public enum ElementType {
End = 0x00, // Marks end of a list
Void = 0x01,
Boolean = 0x02,
Char = 0x03,
I1 = 0x04,
U1 = 0x05,
I2 = 0x06,
U2 = 0x07,
I4 = 0x08,
U4 = 0x09,
I8 = 0x0a,
U8 = 0x0b,
R4 = 0x0c,
R8 = 0x0d,
String = 0x0e,
Ptr = 0x0f, // Followed by <type> token
ByRef = 0x10, // Followed by <type> token
ValueType = 0x11, // Followed by <type> token
Class = 0x12, // Followed by <type> token
Var = 0x13, // Followed by generic parameter number
Array = 0x14, // <type> <rank> <boundsCount> <bound1> <loCount> <lo1>
GenericInst = 0x15, // <type> <type-arg-count> <type-1> ... <type-n> */
TypedByRef = 0x16,
I = 0x18, // System.IntPtr
U = 0x19, // System.UIntPtr
FnPtr = 0x1b, // Followed by full method signature
Object = 0x1c, // System.Object
SzArray = 0x1d, // Single-dim array with 0 lower bound
MVar = 0x1e, // Followed by generic parameter number
CModReqD = 0x1f, // Required modifier : followed by a TypeDef or TypeRef token
CModOpt = 0x20, // Optional modifier : followed by a TypeDef or TypeRef token
Internal = 0x21, // Implemented within the CLI
Modifier = 0x40, // Or'd with following element types
Sentinel = 0x41, // Sentinel for varargs method signature
Pinned = 0x45, // Denotes a local variable that points at a pinned object
// special undocumented constants
Type = 0x50,
Boxed = 0x51,
Enum = 0x55
}
}

55
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/MetadataFormatException.cs

@ -0,0 +1,55 @@ @@ -0,0 +1,55 @@
//
// MetadataFormatException.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Metadata {
using System;
using Mono.Cecil.Binary;
public class MetadataFormatException : ImageFormatException {
internal MetadataFormatException () : base ()
{
}
internal MetadataFormatException (string message) : base (message)
{
}
internal MetadataFormatException (string message, params string [] parameters) :
base (string.Format (message, parameters))
{
}
internal MetadataFormatException (string message, Exception inner) :
base (message, inner)
{
}
}
}

99
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs

@ -0,0 +1,99 @@ @@ -0,0 +1,99 @@
//
// MetadataToken.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Metadata {
public struct MetadataToken {
uint m_rid;
TokenType m_type;
public uint RID {
get { return m_rid; }
}
public TokenType TokenType {
get { return m_type; }
}
public static readonly MetadataToken Zero = new MetadataToken ((TokenType) 0, 0);
public MetadataToken (int token)
{
m_type = (TokenType) (token & 0xff000000);
m_rid = (uint) token & 0x00ffffff;
}
public MetadataToken (TokenType table, uint rid)
{
m_type = table;
m_rid = rid;
}
internal static MetadataToken FromMetadataRow (TokenType table, int rowIndex)
{
return new MetadataToken (table, (uint) rowIndex + 1);
}
public uint ToUInt ()
{
return (uint) m_type | m_rid;
}
public override int GetHashCode ()
{
return (int) ToUInt ();
}
public override bool Equals (object other)
{
if (other is MetadataToken) {
MetadataToken o = (MetadataToken) other;
return o.m_rid == m_rid && o.m_type == m_type;
}
return false;
}
public static bool operator == (MetadataToken one, MetadataToken other)
{
return one.Equals (other);
}
public static bool operator != (MetadataToken one, MetadataToken other)
{
return !one.Equals (other);
}
public override string ToString ()
{
return string.Format ("{0} [0x{1}]",
m_type, m_rid.ToString ("x4"));
}
}
}

58
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs

@ -0,0 +1,58 @@ @@ -0,0 +1,58 @@
//
// TokenType.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Metadata {
public enum TokenType : uint {
Module = 0x00000000,
TypeRef = 0x01000000,
TypeDef = 0x02000000,
Field = 0x04000000,
Method = 0x06000000,
Param = 0x08000000,
InterfaceImpl = 0x09000000,
MemberRef = 0x0a000000,
CustomAttribute = 0x0c000000,
Permission = 0x0e000000,
Signature = 0x11000000,
Event = 0x14000000,
Property = 0x17000000,
ModuleRef = 0x1a000000,
TypeSpec = 0x1b000000,
Assembly = 0x20000000,
AssemblyRef = 0x23000000,
File = 0x26000000,
ExportedType = 0x27000000,
ManifestResource = 0x28000000,
GenericParam = 0x2a000000,
MethodSpec = 0x2b000000,
String = 0x70000000,
Name = 0x71000000,
BaseType = 0x72000000
}
}

649
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs

@ -0,0 +1,649 @@ @@ -0,0 +1,649 @@
//
// Utilities.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Generated by /CodeGen/cecil-gen.rb do not edit
// Tue Jul 17 00:22:33 +0200 2007
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Metadata {
using System;
using System.Collections;
using System.IO;
class Utilities {
Utilities ()
{
}
public static int ReadCompressedInteger (byte [] data, int pos, out int start)
{
int integer = 0;
start = pos;
if ((data [pos] & 0x80) == 0) {
integer = data [pos];
start++;
} else if ((data [pos] & 0x40) == 0) {
integer = (data [start] & ~0x80) << 8;
integer |= data [pos + 1];
start += 2;
} else {
integer = (data [start] & ~0xc0) << 24;
integer |= data [pos + 1] << 16;
integer |= data [pos + 2] << 8;
integer |= data [pos + 3];
start += 4;
}
return integer;
}
public static int WriteCompressedInteger (BinaryWriter writer, int value)
{
if (value < 0x80)
writer.Write ((byte) value);
else if (value < 0x4000) {
writer.Write ((byte) (0x80 | (value >> 8)));
writer.Write ((byte) (value & 0xff));
} else {
writer.Write ((byte) ((value >> 24) | 0xc0));
writer.Write ((byte) ((value >> 16) & 0xff));
writer.Write ((byte) ((value >> 8) & 0xff));
writer.Write ((byte) (value & 0xff));
}
return (int) writer.BaseStream.Position;
}
public static MetadataToken GetMetadataToken (CodedIndex cidx, uint data)
{
uint rid = 0;
switch (cidx) {
case CodedIndex.TypeDefOrRef :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.TypeRef, rid);
case 2 :
return new MetadataToken (TokenType.TypeSpec, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasConstant :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Param, rid);
case 2 :
return new MetadataToken (TokenType.Property, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasCustomAttribute :
rid = data >> 5;
switch (data & 31) {
case 0 :
return new MetadataToken (TokenType.Method, rid);
case 1 :
return new MetadataToken (TokenType.Field, rid);
case 2 :
return new MetadataToken (TokenType.TypeRef, rid);
case 3 :
return new MetadataToken (TokenType.TypeDef, rid);
case 4 :
return new MetadataToken (TokenType.Param, rid);
case 5 :
return new MetadataToken (TokenType.InterfaceImpl, rid);
case 6 :
return new MetadataToken (TokenType.MemberRef, rid);
case 7 :
return new MetadataToken (TokenType.Module, rid);
case 8 :
return new MetadataToken (TokenType.Permission, rid);
case 9 :
return new MetadataToken (TokenType.Property, rid);
case 10 :
return new MetadataToken (TokenType.Event, rid);
case 11 :
return new MetadataToken (TokenType.Signature, rid);
case 12 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 13 :
return new MetadataToken (TokenType.TypeSpec, rid);
case 14 :
return new MetadataToken (TokenType.Assembly, rid);
case 15 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 16 :
return new MetadataToken (TokenType.File, rid);
case 17 :
return new MetadataToken (TokenType.ExportedType, rid);
case 18 :
return new MetadataToken (TokenType.ManifestResource, rid);
case 19 :
return new MetadataToken (TokenType.GenericParam, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasFieldMarshal :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Param, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasDeclSecurity :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
case 2 :
return new MetadataToken (TokenType.Assembly, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.MemberRefParent :
rid = data >> 3;
switch (data & 7) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.TypeRef, rid);
case 2 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 3 :
return new MetadataToken (TokenType.Method, rid);
case 4 :
return new MetadataToken (TokenType.TypeSpec, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasSemantics :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Event, rid);
case 1 :
return new MetadataToken (TokenType.Property, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.MethodDefOrRef :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Method, rid);
case 1 :
return new MetadataToken (TokenType.MemberRef, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.MemberForwarded :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.Implementation :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.File, rid);
case 1 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 2 :
return new MetadataToken (TokenType.ExportedType, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.CustomAttributeType :
rid = data >> 3;
switch (data & 7) {
case 2 :
return new MetadataToken (TokenType.Method, rid);
case 3 :
return new MetadataToken (TokenType.MemberRef, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.ResolutionScope :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.Module, rid);
case 1 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 2 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 3 :
return new MetadataToken (TokenType.TypeRef, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.TypeOrMethodDef :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
default :
return MetadataToken.Zero;
}
default :
return MetadataToken.Zero;
}
}
public static uint CompressMetadataToken (CodedIndex cidx, MetadataToken token)
{
uint ret = 0;
if (token.RID == 0)
return ret;
switch (cidx) {
case CodedIndex.TypeDefOrRef :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.TypeRef :
return ret | 1;
case TokenType.TypeSpec :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for TypeDefOrRef");
}
case CodedIndex.HasConstant :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Param :
return ret | 1;
case TokenType.Property :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for HasConstant");
}
case CodedIndex.HasCustomAttribute :
ret = token.RID << 5;
switch (token.TokenType) {
case TokenType.Method :
return ret | 0;
case TokenType.Field :
return ret | 1;
case TokenType.TypeRef :
return ret | 2;
case TokenType.TypeDef :
return ret | 3;
case TokenType.Param :
return ret | 4;
case TokenType.InterfaceImpl :
return ret | 5;
case TokenType.MemberRef :
return ret | 6;
case TokenType.Module :
return ret | 7;
case TokenType.Permission :
return ret | 8;
case TokenType.Property :
return ret | 9;
case TokenType.Event :
return ret | 10;
case TokenType.Signature :
return ret | 11;
case TokenType.ModuleRef :
return ret | 12;
case TokenType.TypeSpec :
return ret | 13;
case TokenType.Assembly :
return ret | 14;
case TokenType.AssemblyRef :
return ret | 15;
case TokenType.File :
return ret | 16;
case TokenType.ExportedType :
return ret | 17;
case TokenType.ManifestResource :
return ret | 18;
case TokenType.GenericParam :
return ret | 19;
default :
throw new MetadataFormatException("Non valid Token for HasCustomAttribute");
}
case CodedIndex.HasFieldMarshal :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Param :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for HasFieldMarshal");
}
case CodedIndex.HasDeclSecurity :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.Method :
return ret | 1;
case TokenType.Assembly :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for HasDeclSecurity");
}
case CodedIndex.MemberRefParent :
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.TypeRef :
return ret | 1;
case TokenType.ModuleRef :
return ret | 2;
case TokenType.Method :
return ret | 3;
case TokenType.TypeSpec :
return ret | 4;
default :
throw new MetadataFormatException("Non valid Token for MemberRefParent");
}
case CodedIndex.HasSemantics :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Event :
return ret | 0;
case TokenType.Property :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for HasSemantics");
}
case CodedIndex.MethodDefOrRef :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Method :
return ret | 0;
case TokenType.MemberRef :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for MethodDefOrRef");
}
case CodedIndex.MemberForwarded :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Method :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for MemberForwarded");
}
case CodedIndex.Implementation :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.File :
return ret | 0;
case TokenType.AssemblyRef :
return ret | 1;
case TokenType.ExportedType :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for Implementation");
}
case CodedIndex.CustomAttributeType :
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.Method :
return ret | 2;
case TokenType.MemberRef :
return ret | 3;
default :
throw new MetadataFormatException("Non valid Token for CustomAttributeType");
}
case CodedIndex.ResolutionScope :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Module :
return ret | 0;
case TokenType.ModuleRef :
return ret | 1;
case TokenType.AssemblyRef :
return ret | 2;
case TokenType.TypeRef :
return ret | 3;
default :
throw new MetadataFormatException("Non valid Token for ResolutionScope");
}
case CodedIndex.TypeOrMethodDef :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.Method :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for TypeOrMethodDef");
}
default :
throw new MetadataFormatException ("Non valid CodedIndex");
}
}
/*
internal static Type GetCorrespondingTable (TokenType t)
{
switch (t) {
case TokenType.Assembly :
return typeof (AssemblyTable);
case TokenType.AssemblyRef :
return typeof (AssemblyRefTable);
case TokenType.CustomAttribute :
return typeof (CustomAttributeTable);
case TokenType.Event :
return typeof (EventTable);
case TokenType.ExportedType :
return typeof (ExportedTypeTable);
case TokenType.Field :
return typeof (FieldTable);
case TokenType.File :
return typeof (FileTable);
case TokenType.InterfaceImpl :
return typeof (InterfaceImplTable);
case TokenType.MemberRef :
return typeof (MemberRefTable);
case TokenType.Method :
return typeof (MethodTable);
case TokenType.Module :
return typeof (ModuleTable);
case TokenType.ModuleRef :
return typeof (ModuleRefTable);
case TokenType.Param :
return typeof (ParamTable);
case TokenType.Permission :
return typeof (DeclSecurityTable);
case TokenType.Property :
return typeof (PropertyTable);
case TokenType.Signature :
return typeof (StandAloneSigTable);
case TokenType.TypeDef :
return typeof (TypeDefTable);
case TokenType.TypeRef :
return typeof (TypeRefTable);
case TokenType.TypeSpec :
return typeof (TypeSpecTable);
default :
return null;
}
}
internal delegate int TableRowCounter (int rid);
internal static int GetCodedIndexSize (CodedIndex ci, TableRowCounter rowCounter, IDictionary codedIndexCache)
{
int bits = 0, max = 0;
if (codedIndexCache [ci] != null)
return (int) codedIndexCache [ci];
int res = 0;
int [] rids;
switch (ci) {
case CodedIndex.TypeDefOrRef :
bits = 2;
rids = new int [3];
rids [0] = TypeDefTable.RId;
rids [1] = TypeRefTable.RId;
rids [2] = TypeSpecTable.RId;
break;
case CodedIndex.HasConstant :
bits = 2;
rids = new int [3];
rids [0] = FieldTable.RId;
rids [1] = ParamTable.RId;
rids [2] = PropertyTable.RId;
break;
case CodedIndex.HasCustomAttribute :
bits = 5;
rids = new int [20];
rids [0] = MethodTable.RId;
rids [1] = FieldTable.RId;
rids [2] = TypeRefTable.RId;
rids [3] = TypeDefTable.RId;
rids [4] = ParamTable.RId;
rids [5] = InterfaceImplTable.RId;
rids [6] = MemberRefTable.RId;
rids [7] = ModuleTable.RId;
rids [8] = DeclSecurityTable.RId;
rids [9] = PropertyTable.RId;
rids [10] = EventTable.RId;
rids [11] = StandAloneSigTable.RId;
rids [12] = ModuleRefTable.RId;
rids [13] = TypeSpecTable.RId;
rids [14] = AssemblyTable.RId;
rids [15] = AssemblyRefTable.RId;
rids [16] = FileTable.RId;
rids [17] = ExportedTypeTable.RId;
rids [18] = ManifestResourceTable.RId;
rids [19] = GenericParamTable.RId;
break;
case CodedIndex.HasFieldMarshal :
bits = 1;
rids = new int [2];
rids [0] = FieldTable.RId;
rids [1] = ParamTable.RId;
break;
case CodedIndex.HasDeclSecurity :
bits = 2;
rids = new int [3];
rids [0] = TypeDefTable.RId;
rids [1] = MethodTable.RId;
rids [2] = AssemblyTable.RId;
break;
case CodedIndex.MemberRefParent :
bits = 3;
rids = new int [5];
rids [0] = TypeDefTable.RId;
rids [1] = TypeRefTable.RId;
rids [2] = ModuleRefTable.RId;
rids [3] = MethodTable.RId;
rids [4] = TypeSpecTable.RId;
break;
case CodedIndex.HasSemantics :
bits = 1;
rids = new int [2];
rids [0] = EventTable.RId;
rids [1] = PropertyTable.RId;
break;
case CodedIndex.MethodDefOrRef :
bits = 1;
rids = new int [2];
rids [0] = MethodTable.RId;
rids [1] = MemberRefTable.RId;
break;
case CodedIndex.MemberForwarded :
bits = 1;
rids = new int [2];
rids [0] = FieldTable.RId;
rids [1] = MethodTable.RId;
break;
case CodedIndex.Implementation :
bits = 2;
rids = new int [3];
rids [0] = FileTable.RId;
rids [1] = AssemblyRefTable.RId;
rids [2] = ExportedTypeTable.RId;
break;
case CodedIndex.CustomAttributeType :
bits = 3;
rids = new int [2];
rids [0] = MethodTable.RId;
rids [1] = MemberRefTable.RId;
break;
case CodedIndex.ResolutionScope :
bits = 2;
rids = new int [4];
rids [0] = ModuleTable.RId;
rids [1] = ModuleRefTable.RId;
rids [2] = AssemblyRefTable.RId;
rids [3] = TypeRefTable.RId;
break;
case CodedIndex.TypeOrMethodDef :
bits = 1;
rids = new int [2];
rids [0] = TypeDefTable.RId;
rids [1] = MethodTable.RId;
break;
default :
throw new MetadataFormatException ("Non valid CodedIndex");
}
for (int i = 0; i < rids.Length; i++) {
int rows = rowCounter (rids [i]);
if (rows > max) max = rows;
}
res = max < (1 << (16 - bits)) ? 2 : 4;
codedIndexCache [ci] = res;
return res;
}
*/
}
}

43
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Array.cs

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
//
// Array.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 - 2007 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class ARRAY : SigType {
public CustomMod [] CustomMods;
public SigType Type;
public ArrayShape Shape;
public ARRAY () : base (ElementType.Array)
{
}
}
}

43
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/ArrayShape.cs

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
//
// ArrayShape.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class ArrayShape {
public int Rank;
public int NumSizes;
public int [] Sizes;
public int NumLoBounds;
public int [] LoBounds;
public ArrayShape ()
{
}
}
}

53
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/BaseSignatureVisitor.cs

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
//
// BaseSignatureVisitor.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal abstract class BaseSignatureVisitor : ISignatureVisitor {
public virtual void VisitMethodDefSig (MethodDefSig methodDef)
{
}
public virtual void VisitMethodRefSig (MethodRefSig methodRef)
{
}
public virtual void VisitFieldSig (FieldSig field)
{
}
public virtual void VisitPropertySig (PropertySig property)
{
}
public virtual void VisitLocalVarSig (LocalVarSig localvar)
{
}
}
}

41
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Class.cs

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
//
// Class.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class CLASS : SigType {
public MetadataToken Type;
public CLASS () : base (ElementType.Class)
{
}
}
}

37
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Constraint.cs

@ -0,0 +1,37 @@ @@ -0,0 +1,37 @@
//
// Constraints.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal enum Constraint : byte {
None = 0x0,
Pinned = (byte) ElementType.Pinned
}
}

80
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/CustomAttrib.cs

@ -0,0 +1,80 @@ @@ -0,0 +1,80 @@
//
// CustomAttrib.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class CustomAttrib {
public const ushort StdProlog = 0x0001;
public MethodReference Constructor;
public ushort Prolog;
public FixedArg [] FixedArgs;
public ushort NumNamed;
public NamedArg [] NamedArgs;
public bool Read;
public CustomAttrib (MethodReference ctor)
{
Constructor = ctor;
}
public struct FixedArg {
public bool SzArray;
public uint NumElem;
public Elem [] Elems;
}
public struct Elem {
public bool Simple;
public bool String;
public bool Type;
public bool BoxedValueType;
public ElementType FieldOrPropType;
public object Value;
public TypeReference ElemType;
}
public struct NamedArg {
public bool Field;
public bool Property;
public ElementType FieldOrPropType;
public string FieldOrPropName;
public FixedArg FixedArg;
}
}
}

48
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/CustomMod.cs

@ -0,0 +1,48 @@ @@ -0,0 +1,48 @@
//
// CustomMod.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class CustomMod {
public enum CMODType : byte {
None = 0x0,
OPT = (byte) ElementType.CModOpt,
REQD = (byte) ElementType.CModReqD
}
public CMODType CMOD;
public MetadataToken TypeDefOrRef;
public CustomMod ()
{
}
}
}

50
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/FieldSig.cs

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
//
// FieldSig.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class FieldSig : Signature {
public bool Field;
public CustomMod [] CustomMods;
public SigType Type;
public FieldSig () : base ()
{
}
public FieldSig (uint blobIndex) : base (blobIndex)
{
}
public override void Accept (ISignatureVisitor visitor)
{
visitor.VisitFieldSig (this);
}
}
}

41
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/FnPtr.cs

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
//
// FnPtr.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class FNPTR : SigType {
public MethodSig Method;
public FNPTR () : base (ElementType.FnPtr)
{
}
}
}

41
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/GenericArg.cs

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
//
// GenericArg.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2006 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
class GenericArg {
public CustomMod [] CustomMods;
public SigType Type;
public GenericArg (SigType type)
{
Type = type;
}
}
}

46
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/GenericInst.cs

@ -0,0 +1,46 @@ @@ -0,0 +1,46 @@
//
// GenericInst.cs
//
// Author:
// Martin Baulig <baulig@ximian.com>
// Jb Evain <jbevain@gmail.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil;
using Mono.Cecil.Metadata;
internal sealed class GENERICINST : SigType {
public bool ValueType;
public MetadataToken Type;
public GenericInstSignature Signature;
public GENERICINST () : base (ElementType.GenericInst)
{
}
}
}

40
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/GenericInstSignature.cs

@ -0,0 +1,40 @@ @@ -0,0 +1,40 @@
//
// GenericInstSignature.cs
//
// Author:
// Martin Baulig <martin@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class GenericInstSignature {
public int Arity;
public GenericArg [] Types;
public GenericInstSignature ()
{
}
}
}

35
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/ISignatureVisitable.cs

@ -0,0 +1,35 @@ @@ -0,0 +1,35 @@
//
// ISignatureVisitable.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal interface ISignatureVisitable {
void Accept (ISignatureVisitor visitor);
}
}

39
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/ISignatureVisitor.cs

@ -0,0 +1,39 @@ @@ -0,0 +1,39 @@
//
// ISignatureVisitor.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal interface ISignatureVisitor {
void VisitMethodDefSig (MethodDefSig methodDef);
void VisitMethodRefSig (MethodRefSig methodRef);
void VisitFieldSig (FieldSig field);
void VisitPropertySig (PropertySig property);
void VisitLocalVarSig (LocalVarSig localvar);
}
}

38
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/InputOutputItem.cs

@ -0,0 +1,38 @@ @@ -0,0 +1,38 @@
//
// InputOutputItem.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal abstract class InputOutputItem {
public CustomMod [] CustomMods;
public bool ByRef;
public SigType Type;
public bool TypedByRef;
}
}

58
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/LocalVarSig.cs

@ -0,0 +1,58 @@ @@ -0,0 +1,58 @@
//
// LocalVarSig.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class LocalVarSig : Signature {
public bool Local;
public int Count;
public LocalVariable [] LocalVariables;
public LocalVarSig () : base ()
{
}
public LocalVarSig (uint blobIndex) : base (blobIndex)
{
}
public override void Accept (ISignatureVisitor visitor)
{
visitor.VisitLocalVarSig (this);
}
public struct LocalVariable {
public CustomMod [] CustomMods;
public Constraint Constraint;
public bool ByRef;
public SigType Type;
}
}
}

42
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MVar.cs

@ -0,0 +1,42 @@ @@ -0,0 +1,42 @@
//
// MVar.cs
//
// Author:
// Martin Baulig <martin@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class MVAR : SigType {
public int Index;
public MVAR (int index) : base (ElementType.MVar)
{
this.Index = index;
}
}
}

93
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MarshalSig.cs

@ -0,0 +1,93 @@ @@ -0,0 +1,93 @@
//
// MarshalSig.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using System;
using Mono.Cecil;
internal sealed class MarshalSig {
public NativeType NativeInstrinsic;
public IMarshalSigSpec Spec;
public MarshalSig (NativeType nt)
{
this.NativeInstrinsic = nt;
}
public interface IMarshalSigSpec {
}
public sealed class Array : IMarshalSigSpec {
public NativeType ArrayElemType;
public int ParamNum;
public int ElemMult;
public int NumElem;
public Array ()
{
this.ParamNum = 0;
this.ElemMult = 0;
this.NumElem = 0;
}
}
public sealed class CustomMarshaler : IMarshalSigSpec {
public string Guid;
public string UnmanagedType;
public string ManagedType;
public string Cookie;
}
public sealed class FixedArray : IMarshalSigSpec {
public int NumElem;
public NativeType ArrayElemType;
public FixedArray ()
{
this.NumElem = 0;
this.ArrayElemType = NativeType.NONE;
}
}
public sealed class SafeArray : IMarshalSigSpec {
public VariantType ArrayElemType;
}
public sealed class FixedSysString : IMarshalSigSpec {
public int Size;
}
}
}

48
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MethodDefSig.cs

@ -0,0 +1,48 @@ @@ -0,0 +1,48 @@
//
// MethodDefSig.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class MethodDefSig : MethodRefSig {
public int GenericParameterCount;
public MethodDefSig () : this (0)
{
}
public MethodDefSig (uint blobIndex) : base (blobIndex)
{
}
public override void Accept (ISignatureVisitor visitor)
{
visitor.VisitMethodDefSig (this);
}
}
}

49
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MethodRefSig.cs

@ -0,0 +1,49 @@ @@ -0,0 +1,49 @@
//
// MethodRefSig.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal class MethodRefSig : MethodSig {
public int Sentinel;
public MethodRefSig () : this (0)
{
}
public MethodRefSig (uint blobIndex) : base (blobIndex)
{
Sentinel = -1;
}
public override void Accept (ISignatureVisitor visitor)
{
visitor.VisitMethodRefSig (this);
}
}
}

50
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MethodSig.cs

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
//
// MethodSig.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Mono.Cecil;
namespace Mono.Cecil.Signatures {
internal abstract class MethodSig : Signature {
public bool HasThis;
public bool ExplicitThis;
public MethodCallingConvention MethCallConv;
public int ParamCount;
public RetType RetType;
public Param [] Parameters;
public MethodSig () : base ()
{
}
public MethodSig (uint blobIndex) : base (blobIndex)
{
}
}
}

40
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/MethodSpec.cs

@ -0,0 +1,40 @@ @@ -0,0 +1,40 @@
//
// TypeSpec.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class MethodSpec {
public GenericInstSignature Signature;
public MethodSpec (GenericInstSignature sig)
{
this.Signature = sig;
}
}
}

33
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Param.cs

@ -0,0 +1,33 @@ @@ -0,0 +1,33 @@
//
// Param.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class Param : InputOutputItem {
}
}

52
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/PropertySig.cs

@ -0,0 +1,52 @@ @@ -0,0 +1,52 @@
//
// PropertySig.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class PropertySig : Signature {
public bool Property;
public int ParamCount;
public CustomMod [] CustomMods;
public SigType Type;
public Param [] Parameters;
public PropertySig () : base ()
{
}
public PropertySig (uint blobIndex) : base (blobIndex)
{
}
public override void Accept (ISignatureVisitor visitor)
{
visitor.VisitPropertySig (this);
}
}
}

43
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Ptr.cs

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
//
// Ptr.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class PTR : SigType {
public CustomMod [] CustomMods;
public SigType PtrType;
public bool Void;
public PTR () : base (ElementType.Ptr)
{
}
}
}

39
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/RetType.cs

@ -0,0 +1,39 @@ @@ -0,0 +1,39 @@
//
// RetType.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class RetType : InputOutputItem {
public bool Void;
public RetType ()
{
}
}
}

42
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/SigType.cs

@ -0,0 +1,42 @@ @@ -0,0 +1,42 @@
//
// SigType.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal class SigType {
public ElementType ElementType;
public SigType (ElementType elem)
{
ElementType = elem;
}
}
}

50
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Signature.cs

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
//
// Signature.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using System;
internal abstract class Signature : ISignatureVisitable {
public byte CallingConvention;
public uint BlobIndex;
public Signature (uint blobIndex)
{
BlobIndex = blobIndex;
}
public Signature ()
{
BlobIndex = 0;
}
public abstract void Accept (ISignatureVisitor visitor);
}
}

991
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/SignatureReader.cs

@ -0,0 +1,991 @@ @@ -0,0 +1,991 @@
//
// SignatureReader.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 - 2007 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using System;
using System.Collections;
using System.IO;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Metadata;
internal sealed class SignatureReader : BaseSignatureVisitor {
byte [] m_blobData;
IDictionary m_signatures;
public byte[] Blob {
get {
return m_blobData;
}
}
public SignatureReader (byte [] blobData)
{
m_blobData = blobData;
m_signatures = new Hashtable ();
}
/*
MetadataRoot m_root;
ReflectionReader m_reflectReader;
byte [] m_blobData;
IDictionary m_signatures;
IAssemblyResolver AssemblyResolver {
get { return m_reflectReader.Module.Assembly.Resolver; }
}
public SignatureReader (MetadataRoot root, ReflectionReader reflectReader)
{
m_root = root;
m_reflectReader = reflectReader;
m_blobData = m_root.Streams.BlobHeap != null ? m_root.Streams.BlobHeap.Data : new byte [0];
m_signatures = new Hashtable ();
}
*/
public FieldSig GetFieldSig (uint index)
{
FieldSig f = m_signatures [index] as FieldSig;
if (f == null) {
f = new FieldSig (index);
f.Accept (this);
m_signatures [index] = f;
}
return f;
}
public PropertySig GetPropSig (uint index)
{
PropertySig p = m_signatures [index] as PropertySig;
if (p == null) {
p = new PropertySig (index);
p.Accept (this);
m_signatures [index] = p;
}
return p;
}
public MethodDefSig GetMethodDefSig (uint index)
{
MethodDefSig m = m_signatures [index] as MethodDefSig;
if (m == null) {
m = new MethodDefSig (index);
m.Accept (this);
m_signatures [index] = m;
}
return m;
}
public MethodRefSig GetMethodRefSig (uint index)
{
MethodRefSig m = m_signatures [index] as MethodRefSig;
if (m == null) {
m = new MethodRefSig (index);
m.Accept (this);
m_signatures [index] = m;
}
return m;
}
public TypeSpec GetTypeSpec (uint index)
{
TypeSpec ts = m_signatures [index] as TypeSpec;
if (ts == null) {
ts = ReadTypeSpec (m_blobData, (int) index);
m_signatures [index] = ts;
}
return ts;
}
public MethodSpec GetMethodSpec (uint index)
{
MethodSpec ms = m_signatures [index] as MethodSpec;
if (ms == null) {
ms = ReadMethodSpec (m_blobData, (int) index);
m_signatures [index] = ms;
}
return ms;
}
public LocalVarSig GetLocalVarSig (uint index)
{
LocalVarSig lv = m_signatures [index] as LocalVarSig;
if (lv == null) {
lv = new LocalVarSig (index);
lv.Accept (this);
m_signatures [index] = lv;
}
return lv;
}
/*
public CustomAttrib GetCustomAttrib (uint index, MethodReference ctor)
{
return GetCustomAttrib (index, ctor, false);
}
public CustomAttrib GetCustomAttrib (uint index, MethodReference ctor, bool resolve)
{
return ReadCustomAttrib ((int) index, ctor, resolve);
}
public CustomAttrib GetCustomAttrib (byte [] data, MethodReference ctor)
{
return GetCustomAttrib (data, ctor, false);
}
public CustomAttrib GetCustomAttrib (byte [] data, MethodReference ctor, bool resolve)
{
BinaryReader br = new BinaryReader (new MemoryStream (data));
return ReadCustomAttrib (br, data, ctor, resolve);
}
*/
public Signature GetMemberRefSig (TokenType tt, uint index)
{
int start, callconv;
Utilities.ReadCompressedInteger (m_blobData, (int) index, out start);
callconv = m_blobData [start];
if ((callconv & 0x5) == 0x5 || (callconv & 0x10) == 0x10) // vararg || generic?
return GetMethodDefSig (index);
if ((callconv & 0x6) != 0) // field ?
return GetFieldSig (index);
switch (tt) {
case TokenType.TypeDef :
case TokenType.TypeRef :
case TokenType.TypeSpec :
return GetMethodRefSig (index);
case TokenType.ModuleRef :
case TokenType.Method :
return GetMethodDefSig (index);
}
return null;
}
/*
public MarshalSig GetMarshalSig (uint index)
{
MarshalSig ms = m_signatures [index] as MarshalSig;
if (ms == null) {
byte [] data = m_root.Streams.BlobHeap.Read (index);
ms = ReadMarshalSig (data);
m_signatures [index] = ms;
}
return ms;
}
*/
public MethodSig GetStandAloneMethodSig (uint index)
{
int start;
if ((m_blobData [index] & 0x5) > 0) {
MethodRefSig mrs = new MethodRefSig (index);
ReadMethodRefSig (mrs, m_blobData, (int)index, out start);
return mrs;
} else {
MethodDefSig mds = new MethodDefSig (index);
ReadMethodDefSig (mds, m_blobData, (int)index, out start);
return mds;
}
}
public override void VisitMethodDefSig (MethodDefSig methodDef)
{
int start;
ReadMethodDefSig (methodDef, m_blobData, (int)methodDef.BlobIndex, out start);
}
public override void VisitMethodRefSig (MethodRefSig methodRef)
{
int start;
ReadMethodRefSig (methodRef, m_blobData, (int)methodRef.BlobIndex, out start);
}
public override void VisitFieldSig (FieldSig field)
{
int start = 0;
//Utilities.ReadCompressedInteger (m_blobData, (int) field.BlobIndex, out start);
//field.CallingConvention = m_blobData [start];
field.Field = (field.CallingConvention & 0x6) != 0;
field.CustomMods = ReadCustomMods (m_blobData, start + 1, out start);
field.Type = ReadType (m_blobData, start, out start);
}
public override void VisitPropertySig (PropertySig property)
{
int start;
Utilities.ReadCompressedInteger (m_blobData, (int) property.BlobIndex, out start);
property.CallingConvention = m_blobData [start];
property.Property = (property.CallingConvention & 0x8) != 0;
property.ParamCount = Utilities.ReadCompressedInteger (m_blobData, start + 1, out start);
property.CustomMods = ReadCustomMods (m_blobData, start, out start);
property.Type = ReadType (m_blobData, start, out start);
property.Parameters = ReadParameters (property.ParamCount, m_blobData, start);
}
public override void VisitLocalVarSig (LocalVarSig localvar)
{
int start;
Utilities.ReadCompressedInteger (m_blobData, (int) localvar.BlobIndex, out start);
localvar.CallingConvention = m_blobData [start];
localvar.Local = (localvar.CallingConvention & 0x7) != 0;
localvar.Count = Utilities.ReadCompressedInteger (m_blobData, start + 1, out start);
localvar.LocalVariables = ReadLocalVariables (localvar.Count, m_blobData, start);
}
void ReadMethodDefSig (MethodDefSig methodDef, byte [] data, int pos, out int start)
{
methodDef.CallingConvention = data [pos];
start = pos + 1;
methodDef.HasThis = (methodDef.CallingConvention & 0x20) != 0;
methodDef.ExplicitThis = (methodDef.CallingConvention & 0x40) != 0;
if ((methodDef.CallingConvention & 0x5) != 0)
methodDef.MethCallConv |= MethodCallingConvention.VarArg;
else if ((methodDef.CallingConvention & 0x10) != 0) {
methodDef.MethCallConv |= MethodCallingConvention.Generic;
methodDef.GenericParameterCount = Utilities.ReadCompressedInteger (data, start, out start);
} else
methodDef.MethCallConv |= MethodCallingConvention.Default;
methodDef.ParamCount = Utilities.ReadCompressedInteger (data, start, out start);
methodDef.RetType = ReadRetType (data, start, out start);
int sentpos;
methodDef.Parameters = ReadParameters (methodDef.ParamCount, data, start, out sentpos);
methodDef.Sentinel = sentpos;
}
void ReadMethodRefSig (MethodRefSig methodRef, byte [] data, int pos, out int start)
{
methodRef.CallingConvention = data [pos];
start = pos + 1;
methodRef.HasThis = (methodRef.CallingConvention & 0x20) != 0;
methodRef.ExplicitThis = (methodRef.CallingConvention & 0x40) != 0;
if ((methodRef.CallingConvention & 0x1) != 0)
methodRef.MethCallConv |= MethodCallingConvention.C;
else if ((methodRef.CallingConvention & 0x2) != 0)
methodRef.MethCallConv |= MethodCallingConvention.StdCall;
else if ((methodRef.CallingConvention & 0x3) != 0)
methodRef.MethCallConv |= MethodCallingConvention.ThisCall;
else if ((methodRef.CallingConvention & 0x4) != 0)
methodRef.MethCallConv |= MethodCallingConvention.FastCall;
else if ((methodRef.CallingConvention & 0x5) != 0)
methodRef.MethCallConv |= MethodCallingConvention.VarArg;
else
methodRef.MethCallConv |= MethodCallingConvention.Default;
methodRef.ParamCount = Utilities.ReadCompressedInteger (data, start, out start);
methodRef.RetType = ReadRetType (data, start, out start);
int sentpos;
methodRef.Parameters = ReadParameters (methodRef.ParamCount, data, start, out sentpos);
methodRef.Sentinel = sentpos;
}
LocalVarSig.LocalVariable [] ReadLocalVariables (int length, byte [] data, int pos)
{
int start = pos;
LocalVarSig.LocalVariable [] types = new LocalVarSig.LocalVariable [length];
for (int i = 0; i < length; i++)
types [i] = ReadLocalVariable (data, start, out start);
return types;
}
public LocalVarSig.LocalVariable ReadLocalVariable (byte [] data, int pos, out int start)
{
start = pos;
LocalVarSig.LocalVariable lv = new LocalVarSig.LocalVariable ();
lv.ByRef = false;
int cursor;
while (true) {
lv.CustomMods = ReadCustomMods (data, start, out start);
cursor = start;
int current = Utilities.ReadCompressedInteger (data, start, out start);
if (current == (int) ElementType.Pinned) // the only possible constraint
lv.Constraint |= Constraint.Pinned;
else if (current == (int) ElementType.ByRef) {
lv.ByRef = true;
if (lv.CustomMods == null || lv.CustomMods.Length == 0)
lv.CustomMods = ReadCustomMods (data, start, out start);
} else {
lv.Type = ReadType (data, cursor, out start);
break;
}
}
return lv;
}
TypeSpec ReadTypeSpec (byte [] data, int pos)
{
int start = pos;
Utilities.ReadCompressedInteger (data, start, out start);
TypeSpec ts = new TypeSpec ();
ts.CustomMods = ReadCustomMods (data, start, out start);
ts.Type = ReadType (data, start, out start);
return ts;
}
MethodSpec ReadMethodSpec (byte [] data, int pos)
{
int start = pos;
Utilities.ReadCompressedInteger (data, start, out start);
if (Utilities.ReadCompressedInteger (data, start, out start) != 0x0a)
throw new ReflectionException ("Invalid MethodSpec signature");
return new MethodSpec (ReadGenericInstSignature (data, start, out start));
}
RetType ReadRetType (byte [] data, int pos, out int start)
{
RetType rt = new RetType ();
start = pos;
rt.CustomMods = ReadCustomMods (data, start, out start);
int curs = start;
ElementType flag = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
switch (flag) {
case ElementType.Void :
rt.ByRef = rt.TypedByRef = false;
rt.Void = true;
break;
case ElementType.TypedByRef :
rt.ByRef = rt.Void = false;
rt.TypedByRef = true;
break;
case ElementType.ByRef :
rt.TypedByRef = rt.Void = false;
rt.ByRef = true;
if (rt.CustomMods == null || rt.CustomMods.Length == 0)
rt.CustomMods = ReadCustomMods (data, start, out start);
rt.Type = ReadType (data, start, out start);
break;
default :
rt.TypedByRef = rt.Void = rt.ByRef = false;
rt.Type = ReadType (data, curs, out start);
break;
}
return rt;
}
Param [] ReadParameters (int length, byte [] data, int pos)
{
Param [] ret = new Param [length];
int start = pos;
for (int i = 0; i < length; i++)
ret [i] = ReadParameter (data, start, out start);
return ret;
}
Param [] ReadParameters (int length, byte [] data, int pos, out int sentinelpos)
{
Param [] ret = new Param [length];
int start = pos;
sentinelpos = -1;
for (int i = 0; i < length; i++) {
int curs = start;
int flag = Utilities.ReadCompressedInteger (data, start, out start);
if (flag == (int) ElementType.Sentinel) {
sentinelpos = i;
curs = start;
}
ret [i] = ReadParameter (data, curs, out start);
}
return ret;
}
Param ReadParameter (byte [] data, int pos, out int start)
{
Param p = new Param ();
start = pos;
p.CustomMods = ReadCustomMods (data, start, out start);
int curs = start;
ElementType flag = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
switch (flag) {
case ElementType.TypedByRef :
p.TypedByRef = true;
p.ByRef = false;
break;
case ElementType.ByRef :
p.TypedByRef = false;
p.ByRef = true;
if (p.CustomMods == null || p.CustomMods.Length == 0)
p.CustomMods = ReadCustomMods (data, start, out start);
p.Type = ReadType (data, start, out start);
break;
default :
p.TypedByRef = false;
p.ByRef = false;
p.Type = ReadType (data, curs, out start);
break;
}
return p;
}
public SigType ReadType (byte [] data, int pos, out int start)
{
start = pos;
ElementType element = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
switch (element) {
case ElementType.ValueType :
VALUETYPE vt = new VALUETYPE ();
vt.Type = Utilities.GetMetadataToken(CodedIndex.TypeDefOrRef,
(uint) Utilities.ReadCompressedInteger (data, start, out start));
return vt;
case ElementType.Class :
CLASS c = new CLASS ();
c.Type = Utilities.GetMetadataToken (CodedIndex.TypeDefOrRef,
(uint) Utilities.ReadCompressedInteger (data, start, out start));
return c;
case ElementType.Ptr :
PTR p = new PTR ();
int buf = start;
int flag = Utilities.ReadCompressedInteger (data, start, out start);
p.Void = flag == (int) ElementType.Void;
if (p.Void)
return p;
start = buf;
p.CustomMods = ReadCustomMods (data, start, out start);
p.PtrType = ReadType (data, start, out start);
return p;
case ElementType.FnPtr :
FNPTR fp = new FNPTR ();
if ((data [start] & 0x5) != 0) {
MethodRefSig mr = new MethodRefSig ((uint) start);
ReadMethodRefSig (mr, data, start, out start);
fp.Method = mr;
} else {
MethodDefSig md = new MethodDefSig ((uint) start);
ReadMethodDefSig (md, data, start, out start);
fp.Method = md;
}
return fp;
case ElementType.Array :
ARRAY ary = new ARRAY ();
ary.CustomMods = ReadCustomMods (data, start, out start);
ArrayShape shape = new ArrayShape ();
ary.Type = ReadType (data, start, out start);
shape.Rank = Utilities.ReadCompressedInteger (data, start, out start);
shape.NumSizes = Utilities.ReadCompressedInteger (data, start, out start);
shape.Sizes = new int [shape.NumSizes];
for (int i = 0; i < shape.NumSizes; i++)
shape.Sizes [i] = Utilities.ReadCompressedInteger (data, start, out start);
shape.NumLoBounds = Utilities.ReadCompressedInteger (data, start, out start);
shape.LoBounds = new int [shape.NumLoBounds];
for (int i = 0; i < shape.NumLoBounds; i++)
shape.LoBounds [i] = Utilities.ReadCompressedInteger (data, start, out start);
ary.Shape = shape;
return ary;
case ElementType.SzArray :
SZARRAY sa = new SZARRAY ();
sa.CustomMods = ReadCustomMods (data, start, out start);
sa.Type = ReadType (data, start, out start);
return sa;
case ElementType.Var:
return new VAR (Utilities.ReadCompressedInteger (data, start, out start));
case ElementType.MVar:
return new MVAR (Utilities.ReadCompressedInteger (data, start, out start));
case ElementType.GenericInst:
GENERICINST ginst = new GENERICINST ();
ginst.ValueType = ((ElementType) Utilities.ReadCompressedInteger (
data, start, out start)) == ElementType.ValueType;
ginst.Type = Utilities.GetMetadataToken (CodedIndex.TypeDefOrRef,
(uint) Utilities.ReadCompressedInteger (data, start, out start));
ginst.Signature = ReadGenericInstSignature (data, start, out start);
return ginst;
default :
return new SigType (element);
}
}
GenericInstSignature ReadGenericInstSignature (byte [] data, int pos, out int start)
{
start = pos;
GenericInstSignature gis = new GenericInstSignature ();
gis.Arity = Utilities.ReadCompressedInteger (data, start, out start);
gis.Types = new GenericArg [gis.Arity];
for (int i = 0; i < gis.Arity; i++)
gis.Types [i] = ReadGenericArg (data, start, out start);
return gis;
}
GenericArg ReadGenericArg (byte[] data, int pos, out int start)
{
start = pos;
CustomMod [] mods = ReadCustomMods (data, start, out start);
GenericArg arg = new GenericArg (ReadType (data, start, out start));
arg.CustomMods = mods;
return arg;
}
CustomMod [] ReadCustomMods (byte [] data, int pos, out int start)
{
ArrayList cmods = new ArrayList ();
start = pos;
while (true) {
int buf = start;
ElementType flag = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
start = buf;
if (!((flag == ElementType.CModOpt) || (flag == ElementType.CModReqD)))
break;
cmods.Add (ReadCustomMod (data, start, out start));
}
return cmods.ToArray (typeof (CustomMod)) as CustomMod [];
}
CustomMod ReadCustomMod (byte [] data, int pos, out int start)
{
CustomMod cm = new CustomMod ();
start = pos;
ElementType cmod = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
if (cmod == ElementType.CModOpt)
cm.CMOD = CustomMod.CMODType.OPT;
else if (cmod == ElementType.CModReqD)
cm.CMOD = CustomMod.CMODType.REQD;
else
cm.CMOD = CustomMod.CMODType.None;
cm.TypeDefOrRef = Utilities.GetMetadataToken (CodedIndex.TypeDefOrRef,
(uint) Utilities.ReadCompressedInteger (data, start, out start));
return cm;
}
/*
CustomAttrib ReadCustomAttrib (int pos, MethodReference ctor, bool resolve)
{
int start, length = Utilities.ReadCompressedInteger (m_blobData, pos, out start);
byte [] data = new byte [length];
Buffer.BlockCopy (m_blobData, start, data, 0, length);
try {
return ReadCustomAttrib (new BinaryReader (
new MemoryStream (data)), data, ctor, resolve);
} catch {
CustomAttrib ca = new CustomAttrib (ctor);
ca.Read = false;
return ca;
}
}
CustomAttrib ReadCustomAttrib (BinaryReader br, byte [] data, MethodReference ctor, bool resolve)
{
CustomAttrib ca = new CustomAttrib (ctor);
if (data.Length == 0) {
ca.FixedArgs = new CustomAttrib.FixedArg [0];
ca.NamedArgs = new CustomAttrib.NamedArg [0];
return ca;
}
bool read = true;
ca.Prolog = br.ReadUInt16 ();
if (ca.Prolog != CustomAttrib.StdProlog)
throw new MetadataFormatException ("Non standard prolog for custom attribute");
ca.FixedArgs = new CustomAttrib.FixedArg [ctor.Parameters.Count];
for (int i = 0; i < ca.FixedArgs.Length && read; i++)
ca.FixedArgs [i] = ReadFixedArg (data, br,
ctor.Parameters [i].ParameterType, ref read, resolve);
if (br.BaseStream.Position == br.BaseStream.Length)
read = false;
if (!read) {
ca.Read = read;
return ca;
}
ca.NumNamed = br.ReadUInt16 ();
ca.NamedArgs = new CustomAttrib.NamedArg [ca.NumNamed];
for (int i = 0; i < ca.NumNamed && read; i++)
ca.NamedArgs [i] = ReadNamedArg (data, br, ref read, resolve);
ca.Read = read;
return ca;
}
CustomAttrib.FixedArg ReadFixedArg (byte [] data, BinaryReader br,
TypeReference param, ref bool read, bool resolve)
{
CustomAttrib.FixedArg fa = new CustomAttrib.FixedArg ();
if (param is ArrayType) {
param = ((ArrayType) param).ElementType;
fa.SzArray = true;
fa.NumElem = br.ReadUInt32 ();
if (fa.NumElem == 0 || fa.NumElem == 0xffffffff) {
fa.Elems = new CustomAttrib.Elem [0];
fa.NumElem = 0;
return fa;
}
fa.Elems = new CustomAttrib.Elem [fa.NumElem];
for (int i = 0; i < fa.NumElem; i++)
fa.Elems [i] = ReadElem (data, br, param, ref read, resolve);
} else
fa.Elems = new CustomAttrib.Elem [] { ReadElem (data, br, param, ref read, resolve) };
return fa;
}
TypeReference CreateEnumTypeReference (string enumName)
{
string asmName = null;
int asmStart = enumName.IndexOf (',');
if (asmStart != -1) {
asmName = enumName.Substring (asmStart + 1);
enumName = enumName.Substring (0, asmStart);
}
// Inner class style is reflection style.
enumName = enumName.Replace ('+', '/');
AssemblyNameReference asm;
if (asmName == null) {
// If no assembly is given then the ECMA standard says the
// assembly is either the current one or mscorlib.
if (m_reflectReader.Module.Types.Contains (enumName))
return m_reflectReader.Module.Types [enumName];
asm = m_reflectReader.Corlib;
} else
asm = AssemblyNameReference.Parse (asmName);
string [] outers = enumName.Split ('/');
string outerfullname = outers [0];
string ns = null;
int nsIndex = outerfullname.LastIndexOf ('.');
if (nsIndex != -1)
ns = outerfullname.Substring (0, nsIndex);
string name = outerfullname.Substring (nsIndex + 1);
TypeReference decType = new TypeReference (name, ns, asm);
for (int i = 1; i < outers.Length; i++) {
TypeReference t = new TypeReference (outers [i], null, asm);
t.DeclaringType = decType;
decType = t;
}
decType.IsValueType = true;
return decType;
}
TypeReference ReadTypeReference (byte [] data, BinaryReader br, out ElementType elemType)
{
bool array = false;
elemType = (ElementType) br.ReadByte ();
if (elemType == ElementType.SzArray) {
elemType = (ElementType) br.ReadByte ();
array = true;
}
TypeReference res;
if (elemType == ElementType.Enum)
res = CreateEnumTypeReference (ReadUTF8String (data, br));
else
res = TypeReferenceFromElemType (elemType);
if (array)
res = new ArrayType (res);
return res;
}
TypeReference TypeReferenceFromElemType (ElementType elemType)
{
switch (elemType) {
case ElementType.Boxed :
return m_reflectReader.SearchCoreType (Constants.Object);
case ElementType.String :
return m_reflectReader.SearchCoreType (Constants.String);
case ElementType.Type :
return m_reflectReader.SearchCoreType (Constants.Type);
case ElementType.Boolean :
return m_reflectReader.SearchCoreType (Constants.Boolean);
case ElementType.Char :
return m_reflectReader.SearchCoreType (Constants.Char);
case ElementType.R4 :
return m_reflectReader.SearchCoreType (Constants.Single);
case ElementType.R8 :
return m_reflectReader.SearchCoreType (Constants.Double);
case ElementType.I1 :
return m_reflectReader.SearchCoreType (Constants.SByte);
case ElementType.I2 :
return m_reflectReader.SearchCoreType (Constants.Int16);
case ElementType.I4 :
return m_reflectReader.SearchCoreType (Constants.Int32);
case ElementType.I8 :
return m_reflectReader.SearchCoreType (Constants.Int64);
case ElementType.U1 :
return m_reflectReader.SearchCoreType (Constants.Byte);
case ElementType.U2 :
return m_reflectReader.SearchCoreType (Constants.UInt16);
case ElementType.U4 :
return m_reflectReader.SearchCoreType (Constants.UInt32);
case ElementType.U8 :
return m_reflectReader.SearchCoreType (Constants.UInt64);
default :
throw new MetadataFormatException ("Non valid type in CustomAttrib.Elem: 0x{0}",
((byte) elemType).ToString("x2"));
}
}
internal CustomAttrib.NamedArg ReadNamedArg (byte [] data, BinaryReader br, ref bool read, bool resolve)
{
CustomAttrib.NamedArg na = new CustomAttrib.NamedArg ();
byte kind = br.ReadByte ();
if (kind == 0x53) { // field
na.Field = true;
na.Property = false;
} else if (kind == 0x54) { // property
na.Field = false;
na.Property = true;
} else
throw new MetadataFormatException ("Wrong kind of namedarg found: 0x" + kind.ToString("x2"));
TypeReference elemType = ReadTypeReference (data, br, out na.FieldOrPropType);
na.FieldOrPropName = ReadUTF8String (data, br);
na.FixedArg = ReadFixedArg (data, br, elemType, ref read, resolve);
return na;
}
CustomAttrib.Elem ReadElem (byte [] data, BinaryReader br, TypeReference elemType, ref bool read, bool resolve)
{
CustomAttrib.Elem elem = new CustomAttrib.Elem ();
string elemName = elemType.FullName;
if (elemName == Constants.Object) {
elemType = ReadTypeReference (data, br, out elem.FieldOrPropType);
if (elemType is ArrayType) {
read = false; // Don't know how to represent arrays as an object value.
return elem;
} else if (elemType.FullName == Constants.Object)
throw new MetadataFormatException ("Non valid type in CustomAttrib.Elem after boxed prefix: 0x{0}",
((byte) elem.FieldOrPropType).ToString("x2"));
elem = ReadElem (data, br, elemType, ref read, resolve);
elem.String = elem.Simple = elem.Type = false;
elem.BoxedValueType = true;
return elem;
}
elem.ElemType = elemType;
if (elemName == Constants.Type || elemName == Constants.String) {
switch (elemType.FullName) {
case Constants.String:
elem.String = true;
elem.BoxedValueType = elem.Simple = elem.Type = false;
break;
case Constants.Type:
elem.Type = true;
elem.BoxedValueType = elem.Simple = elem.String = false;
break;
}
if (data [br.BaseStream.Position] == 0xff) { // null
elem.Value = null;
br.BaseStream.Position++;
} else {
elem.Value = ReadUTF8String (data, br);
}
return elem;
}
elem.String = elem.Type = elem.BoxedValueType = false;
if (!ReadSimpleValue (br, ref elem, elem.ElemType)) {
if (!resolve) { // until enums writing is implemented
read = false;
return elem;
}
TypeReference typeRef = GetEnumUnderlyingType (elem.ElemType, resolve);
if (typeRef == null || !ReadSimpleValue (br, ref elem, typeRef))
read = false;
}
return elem;
}
TypeReference GetEnumUnderlyingType (TypeReference enumType, bool resolve)
{
TypeDefinition type = enumType as TypeDefinition;
if (type == null && resolve && AssemblyResolver != null) {
if (enumType.Scope is ModuleDefinition)
throw new NotSupportedException ();
AssemblyDefinition asm = AssemblyResolver.Resolve (
((AssemblyNameReference) enumType.Scope).FullName);
type = asm.MainModule.Types [enumType.FullName];
}
if (type != null && type.IsEnum)
return type.Fields.GetField ("value__").FieldType;
return null;
}
bool ReadSimpleValue (BinaryReader br, ref CustomAttrib.Elem elem, TypeReference type)
{
switch (type.FullName) {
case Constants.Boolean :
elem.Value = br.ReadByte () == 1;
break;
case Constants.Char :
elem.Value = (char) br.ReadUInt16 ();
break;
case Constants.Single :
elem.Value = br.ReadSingle ();
break;
case Constants.Double :
elem.Value = br.ReadDouble ();
break;
case Constants.Byte :
elem.Value = br.ReadByte ();
break;
case Constants.Int16 :
elem.Value = br.ReadInt16 ();
break;
case Constants.Int32 :
elem.Value = br.ReadInt32 ();
break;
case Constants.Int64 :
elem.Value = br.ReadInt64 ();
break;
case Constants.SByte :
elem.Value = br.ReadSByte ();
break;
case Constants.UInt16 :
elem.Value = br.ReadUInt16 ();
break;
case Constants.UInt32 :
elem.Value = br.ReadUInt32 ();
break;
case Constants.UInt64 :
elem.Value = br.ReadUInt64 ();
break;
default : // enum
return false;
}
elem.Simple = true;
return true;
}
MarshalSig ReadMarshalSig (byte [] data)
{
int start;
MarshalSig ms = new MarshalSig ((NativeType) Utilities.ReadCompressedInteger (data, 0, out start));
switch (ms.NativeInstrinsic) {
case NativeType.ARRAY:
MarshalSig.Array ar = new MarshalSig.Array ();
ar.ArrayElemType = (NativeType) Utilities.ReadCompressedInteger (data, start, out start);
if (start < data.Length)
ar.ParamNum = Utilities.ReadCompressedInteger (data, start, out start);
if (start < data.Length)
ar.NumElem = Utilities.ReadCompressedInteger (data, start, out start);
if (start < data.Length)
ar.ElemMult = Utilities.ReadCompressedInteger (data, start, out start);
ms.Spec = ar;
break;
case NativeType.CUSTOMMARSHALER:
MarshalSig.CustomMarshaler cm = new MarshalSig.CustomMarshaler ();
cm.Guid = ReadUTF8String (data, start, out start);
cm.UnmanagedType = ReadUTF8String (data, start, out start);
cm.ManagedType = ReadUTF8String (data, start, out start);
cm.Cookie = ReadUTF8String (data, start, out start);
ms.Spec = cm;
break;
case NativeType.FIXEDARRAY:
MarshalSig.FixedArray fa = new MarshalSig.FixedArray ();
fa.NumElem = Utilities.ReadCompressedInteger (data, start, out start);
if (start < data.Length)
fa.ArrayElemType = (NativeType) Utilities.ReadCompressedInteger (data, start, out start);
ms.Spec = fa;
break;
case NativeType.SAFEARRAY:
MarshalSig.SafeArray sa = new MarshalSig.SafeArray ();
if (start < data.Length)
sa.ArrayElemType = (VariantType) Utilities.ReadCompressedInteger (data, start, out start);
ms.Spec = sa;
break;
case NativeType.FIXEDSYSSTRING:
MarshalSig.FixedSysString fss = new MarshalSig.FixedSysString ();
if (start < data.Length)
fss.Size = Utilities.ReadCompressedInteger (data, start, out start);
ms.Spec = fss;
break;
}
return ms;
}
static internal string ReadUTF8String (byte [] data, BinaryReader br)
{
int start = (int)br.BaseStream.Position;
string val = ReadUTF8String (data, start, out start);
br.BaseStream.Position = start;
return val;
}
static internal string ReadUTF8String (byte [] data, int pos, out int start)
{
int length = Utilities.ReadCompressedInteger (data, pos, out start);
pos = start;
start += length;
// COMPACT FRAMEWORK NOTE: Encoding.GetString (byte[]) is not supported.
return Encoding.UTF8.GetString (data, pos, length);
}
*/
}
}

520
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/SignatureWriter.cs

@ -0,0 +1,520 @@ @@ -0,0 +1,520 @@
//
// SignatureWriter.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 - 2007 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using System;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Binary;
using Mono.Cecil.Metadata;
internal sealed class SignatureWriter : BaseSignatureVisitor {
MetadataWriter m_mdWriter;
MemoryBinaryWriter m_sigWriter;
public SignatureWriter (MetadataWriter mdWriter)
{
m_mdWriter = mdWriter;
m_sigWriter = new MemoryBinaryWriter ();
}
uint GetPointer ()
{
return m_mdWriter.AddBlob (m_sigWriter.ToArray ());
}
public uint AddMethodDefSig (MethodDefSig methSig)
{
return AddSignature (methSig);
}
public uint AddMethodRefSig (MethodRefSig methSig)
{
return AddSignature (methSig);
}
public uint AddPropertySig (PropertySig ps)
{
return AddSignature (ps);
}
public uint AddFieldSig (FieldSig fSig)
{
return AddSignature (fSig);
}
public uint AddLocalVarSig (LocalVarSig lvs)
{
return AddSignature (lvs);
}
uint AddSignature (Signature s)
{
m_sigWriter.Empty ();
s.Accept (this);
return GetPointer ();
}
public uint AddTypeSpec (TypeSpec ts)
{
m_sigWriter.Empty ();
Write (ts);
return GetPointer ();
}
public uint AddMethodSpec (MethodSpec ms)
{
m_sigWriter.Empty ();
Write (ms);
return GetPointer ();
}
public uint AddMarshalSig (MarshalSig ms)
{
m_sigWriter.Empty ();
Write (ms);
return GetPointer ();
}
public uint AddCustomAttribute (CustomAttrib ca, MethodReference ctor)
{
CompressCustomAttribute (ca, ctor, m_sigWriter);
return GetPointer ();
}
public byte [] CompressCustomAttribute (CustomAttrib ca, MethodReference ctor)
{
MemoryBinaryWriter writer = new MemoryBinaryWriter ();
CompressCustomAttribute (ca, ctor, writer);
return writer.ToArray ();
}
public byte [] CompressFieldSig (FieldSig field)
{
m_sigWriter.Empty ();
VisitFieldSig (field);
return m_sigWriter.ToArray ();
}
public byte [] CompressLocalVar (LocalVarSig.LocalVariable var)
{
m_sigWriter.Empty ();
Write (var);
return m_sigWriter.ToArray ();
}
void CompressCustomAttribute (CustomAttrib ca, MethodReference ctor, MemoryBinaryWriter writer)
{
m_sigWriter.Empty ();
Write (ca, ctor, writer);
}
public override void VisitMethodDefSig (MethodDefSig methodDef)
{
m_sigWriter.Write (methodDef.CallingConvention);
if (methodDef.GenericParameterCount > 0)
Write (methodDef.GenericParameterCount);
Write (methodDef.ParamCount);
Write (methodDef.RetType);
Write (methodDef.Parameters, methodDef.Sentinel);
}
public override void VisitMethodRefSig (MethodRefSig methodRef)
{
m_sigWriter.Write (methodRef.CallingConvention);
Write (methodRef.ParamCount);
Write (methodRef.RetType);
Write (methodRef.Parameters, methodRef.Sentinel);
}
public override void VisitFieldSig (FieldSig field)
{
m_sigWriter.Write (field.CallingConvention);
Write (field.CustomMods);
Write (field.Type);
}
public override void VisitPropertySig (PropertySig property)
{
m_sigWriter.Write (property.CallingConvention);
Write (property.ParamCount);
Write (property.CustomMods);
Write (property.Type);
Write (property.Parameters);
}
public override void VisitLocalVarSig (LocalVarSig localvar)
{
m_sigWriter.Write (localvar.CallingConvention);
Write (localvar.Count);
Write (localvar.LocalVariables);
}
void Write (LocalVarSig.LocalVariable [] vars)
{
foreach (LocalVarSig.LocalVariable var in vars)
Write (var);
}
void Write (LocalVarSig.LocalVariable var)
{
Write (var.CustomMods);
if ((var.Constraint & Constraint.Pinned) != 0)
Write (ElementType.Pinned);
if (var.ByRef)
Write (ElementType.ByRef);
Write (var.Type);
}
void Write (RetType retType)
{
Write (retType.CustomMods);
if (retType.Void)
Write (ElementType.Void);
else if (retType.TypedByRef)
Write (ElementType.TypedByRef);
else if (retType.ByRef) {
Write (ElementType.ByRef);
Write (retType.Type);
} else
Write (retType.Type);
}
void Write (Param [] parameters, int sentinel)
{
for (int i = 0; i < parameters.Length; i++) {
if (i == sentinel)
Write (ElementType.Sentinel);
Write (parameters [i]);
}
}
void Write (Param [] parameters)
{
foreach (Param p in parameters)
Write (p);
}
void Write (ElementType et)
{
Write ((int) et);
}
void Write (SigType t)
{
Write ((int) t.ElementType);
switch (t.ElementType) {
case ElementType.ValueType :
Write ((int) Utilities.CompressMetadataToken (
CodedIndex.TypeDefOrRef, ((VALUETYPE) t).Type));
break;
case ElementType.Class :
Write ((int) Utilities.CompressMetadataToken (
CodedIndex.TypeDefOrRef, ((CLASS) t).Type));
break;
case ElementType.Ptr :
PTR p = (PTR) t;
if (p.Void)
Write (ElementType.Void);
else {
Write (p.CustomMods);
Write (p.PtrType);
}
break;
case ElementType.FnPtr :
FNPTR fp = (FNPTR) t;
if (fp.Method is MethodRefSig)
(fp.Method as MethodRefSig).Accept (this);
else
(fp.Method as MethodDefSig).Accept (this);
break;
case ElementType.Array :
ARRAY ary = (ARRAY) t;
Write (ary.CustomMods);
ArrayShape shape = ary.Shape;
Write (ary.Type);
Write (shape.Rank);
Write (shape.NumSizes);
foreach (int size in shape.Sizes)
Write (size);
Write (shape.NumLoBounds);
foreach (int loBound in shape.LoBounds)
Write (loBound);
break;
case ElementType.SzArray :
SZARRAY sa = (SZARRAY) t;
Write (sa.CustomMods);
Write (sa.Type);
break;
case ElementType.Var :
Write (((VAR) t).Index);
break;
case ElementType.MVar :
Write (((MVAR) t).Index);
break;
case ElementType.GenericInst :
GENERICINST gi = t as GENERICINST;
Write (gi.ValueType ? ElementType.ValueType : ElementType.Class);
Write ((int) Utilities.CompressMetadataToken (
CodedIndex.TypeDefOrRef, gi.Type));
Write (gi.Signature);
break;
}
}
void Write (TypeSpec ts)
{
Write (ts.CustomMods);
Write (ts.Type);
}
void Write (MethodSpec ms)
{
Write (0x0a);
Write (ms.Signature);
}
void Write (GenericInstSignature gis)
{
Write (gis.Arity);
for (int i = 0; i < gis.Arity; i++)
Write (gis.Types [i]);
}
void Write (GenericArg arg)
{
Write (arg.CustomMods);
Write (arg.Type);
}
void Write (Param p)
{
Write (p.CustomMods);
if (p.TypedByRef)
Write (ElementType.TypedByRef);
else if (p.ByRef) {
Write (ElementType.ByRef);
Write (p.Type);
} else
Write (p.Type);
}
void Write (CustomMod [] customMods)
{
foreach (CustomMod cm in customMods)
Write (cm);
}
void Write (CustomMod cm)
{
switch (cm.CMOD) {
case CustomMod.CMODType.OPT :
Write (ElementType.CModOpt);
break;
case CustomMod.CMODType.REQD :
Write (ElementType.CModReqD);
break;
}
Write ((int) Utilities.CompressMetadataToken (
CodedIndex.TypeDefOrRef, cm.TypeDefOrRef));
}
void Write (MarshalSig ms)
{
Write ((int) ms.NativeInstrinsic);
switch (ms.NativeInstrinsic) {
case NativeType.ARRAY :
MarshalSig.Array ar = (MarshalSig.Array) ms.Spec;
Write ((int) ar.ArrayElemType);
if (ar.ParamNum != -1)
Write (ar.ParamNum);
if (ar.NumElem != -1)
Write (ar.NumElem);
if (ar.ElemMult != -1)
Write (ar.ElemMult);
break;
case NativeType.CUSTOMMARSHALER :
MarshalSig.CustomMarshaler cm = (MarshalSig.CustomMarshaler) ms.Spec;
Write (cm.Guid);
Write (cm.UnmanagedType);
Write (cm.ManagedType);
Write (cm.Cookie);
break;
case NativeType.FIXEDARRAY :
MarshalSig.FixedArray fa = (MarshalSig.FixedArray) ms.Spec;
Write (fa.NumElem);
if (fa.ArrayElemType != NativeType.NONE)
Write ((int) fa.ArrayElemType);
break;
case NativeType.SAFEARRAY :
Write ((int) ((MarshalSig.SafeArray) ms.Spec).ArrayElemType);
break;
case NativeType.FIXEDSYSSTRING :
Write (((MarshalSig.FixedSysString) ms.Spec).Size);
break;
}
}
void Write (CustomAttrib ca, MethodReference ctor, MemoryBinaryWriter writer)
{
if (ca == null)
return;
if (ca.Prolog != CustomAttrib.StdProlog)
return;
writer.Write (ca.Prolog);
for (int i = 0; i < ctor.Parameters.Count; i++)
Write (ca.FixedArgs [i], writer);
writer.Write (ca.NumNamed);
for (int i = 0; i < ca.NumNamed; i++)
Write (ca.NamedArgs [i], writer);
}
void Write (CustomAttrib.FixedArg fa, MemoryBinaryWriter writer)
{
if (fa.SzArray)
writer.Write (fa.NumElem);
foreach (CustomAttrib.Elem elem in fa.Elems)
Write (elem, writer);
}
void Write (CustomAttrib.NamedArg na, MemoryBinaryWriter writer)
{
if (na.Field)
writer.Write ((byte) 0x53);
else if (na.Property)
writer.Write ((byte) 0x54);
else
throw new MetadataFormatException ("Unknown kind of namedarg");
if (na.FixedArg.SzArray)
writer.Write ((byte) ElementType.SzArray);
if (na.FieldOrPropType == ElementType.Object)
writer.Write ((byte) ElementType.Boxed);
else
writer.Write ((byte) na.FieldOrPropType);
if (na.FieldOrPropType == ElementType.Enum)
Write (na.FixedArg.Elems [0].ElemType.FullName);
Write (na.FieldOrPropName);
Write (na.FixedArg, writer);
}
void Write (CustomAttrib.Elem elem, MemoryBinaryWriter writer) // TODO
{
if (elem.String)
elem.FieldOrPropType = ElementType.String;
else if (elem.Type)
elem.FieldOrPropType = ElementType.Type;
else if (elem.BoxedValueType)
Write (elem.FieldOrPropType);
switch (elem.FieldOrPropType) {
case ElementType.Boolean :
writer.Write ((byte) ((bool) elem.Value ? 1 : 0));
break;
case ElementType.Char :
writer.Write ((ushort) (char) elem.Value);
break;
case ElementType.R4 :
writer.Write ((float) elem.Value);
break;
case ElementType.R8 :
writer.Write ((double) elem.Value);
break;
case ElementType.I1 :
writer.Write ((sbyte) elem.Value);
break;
case ElementType.I2 :
writer.Write ((short) elem.Value);
break;
case ElementType.I4 :
writer.Write ((int) elem.Value);
break;
case ElementType.I8 :
writer.Write ((long) elem.Value);
break;
case ElementType.U1 :
writer.Write ((byte) elem.Value);
break;
case ElementType.U2 :
writer.Write ((ushort) elem.Value);
break;
case ElementType.U4 :
writer.Write ((uint) elem.Value);
break;
case ElementType.U8 :
writer.Write ((long) elem.Value);
break;
case ElementType.String :
case ElementType.Type :
string s = elem.Value as string;
if (s == null)
writer.Write ((byte) 0xff);
else if (s.Length == 0)
writer.Write ((byte) 0x00);
else
Write (s);
break;
case ElementType.Object :
if (elem.Value != null)
throw new NotSupportedException ("Unknown state");
writer.Write ((byte) 0xff);
break;
default :
throw new NotImplementedException ("WriteElem " + elem.FieldOrPropType.ToString ());
}
}
void Write (string s)
{
byte [] str = Encoding.UTF8.GetBytes (s);
Write (str.Length);
m_sigWriter.Write (str);
}
void Write (int i)
{
Utilities.WriteCompressedInteger (m_sigWriter, i);
}
}
}

42
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/SzArray.cs

@ -0,0 +1,42 @@ @@ -0,0 +1,42 @@
//
// SzArray.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 - 2007 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class SZARRAY : SigType {
public CustomMod [] CustomMods;
public SigType Type;
public SZARRAY () : base (ElementType.SzArray)
{
}
}
}

36
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/TypeSpec.cs

@ -0,0 +1,36 @@ @@ -0,0 +1,36 @@
//
// TypeSpec.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 - 2007 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
internal sealed class TypeSpec {
public CustomMod [] CustomMods;
public SigType Type;
}
}

41
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/ValueType.cs

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
//
// ValueType.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class VALUETYPE : SigType {
public MetadataToken Type;
public VALUETYPE () : base (ElementType.ValueType)
{
}
}
}

42
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil.Signatures/Var.cs

@ -0,0 +1,42 @@ @@ -0,0 +1,42 @@
//
// Var.cs
//
// Author:
// Martin Baulig <martin@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using Mono.Cecil.Metadata;
internal sealed class VAR : SigType {
public int Index;
public VAR (int index) : base (ElementType.Var)
{
this.Index = index;
}
}
}

43
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
//
// MethodCallingConvention.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil {
using System;
[Flags]
public enum MethodCallingConvention : byte {
Default = 0x0,
C = 0x1,
StdCall = 0x2,
ThisCall = 0x3,
FastCall = 0x4,
VarArg = 0x5,
Generic = 0x10
}
}

55
Debugger/Debugger.Core/Mono.Cecil/Mono.Cecil/ReflectionException.cs

@ -0,0 +1,55 @@ @@ -0,0 +1,55 @@
//
// ReflectionException.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil {
using System;
using Mono.Cecil.Metadata;
public sealed class ReflectionException : MetadataFormatException {
internal ReflectionException () : base ()
{
}
internal ReflectionException (string message) : base (message)
{
}
internal ReflectionException (string message, params string [] parameters) :
base (string.Format (message, parameters))
{
}
internal ReflectionException (string message, Exception inner) :
base (message, inner)
{
}
}
}

320
Debugger/Debugger.Core/NDebugger.cs

@ -0,0 +1,320 @@ @@ -0,0 +1,320 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.IO;
using System.Text;
using System.Threading;
using Debugger.Interop;
using Debugger.Interop.CorDebug;
using Microsoft.Win32;
namespace Debugger
{
public class NDebugger: DebuggerObject
{
ICorDebug corDebug;
ManagedCallbackSwitch managedCallbackSwitch;
ManagedCallbackProxy managedCallbackProxy;
BreakpointCollection breakpoints;
ProcessCollection processes;
MTA2STA mta2sta = new MTA2STA();
string debuggeeVersion;
Options options = new Options();
public MTA2STA MTA2STA {
get {
return mta2sta;
}
}
internal ICorDebug CorDebug {
get {
return corDebug;
}
}
public string DebuggeeVersion {
get {
return debuggeeVersion;
}
}
public Options Options {
get { return options; }
set { options = value; }
}
public BreakpointCollection Breakpoints {
get { return breakpoints; }
}
public ProcessCollection Processes {
get { return processes; }
}
public NDebugger()
{
processes = new ProcessCollection(this);
breakpoints = new BreakpointCollection(this);
if (ApartmentState.STA == System.Threading.Thread.CurrentThread.GetApartmentState()) {
mta2sta.CallMethod = CallMethod.HiddenFormWithTimeout;
} else {
mta2sta.CallMethod = CallMethod.DirectCall;
}
}
/// <summary>
/// Get the .NET version of the process that called this function
/// </summary>
public string GetDebuggerVersion()
{
int size;
NativeMethods.GetCORVersion(null, 0, out size);
StringBuilder sb = new StringBuilder(size);
int hr = NativeMethods.GetCORVersion(sb, sb.Capacity, out size);
return sb.ToString();
}
/// <summary>
/// Get the .NET version of a given program - eg. "v1.1.4322"
/// </summary>
/// <remarks> Returns empty string for unmanaged applications </remarks>
public string GetProgramVersion(string exeFilename)
{
int size;
NativeMethods.GetRequestedRuntimeVersion(exeFilename, null, 0, out size);
StringBuilder sb = new StringBuilder(size);
NativeMethods.GetRequestedRuntimeVersion(exeFilename, sb, sb.Capacity, out size);
sb.Length = size;
return sb.ToString().TrimEnd('\0');
}
/// <summary>
/// Prepares the debugger
/// </summary>
/// <param name="debuggeeVersion">Version of the program to debug - eg. "v1.1.4322"
/// If null, the version of the executing process will be used</param>
internal void InitDebugger(string debuggeeVersion)
{
if (IsKernelDebuggerEnabled) {
throw new DebuggerException("Can not debug because kernel debugger is enabled");
}
if (string.IsNullOrEmpty(debuggeeVersion)) {
debuggeeVersion = GetDebuggerVersion();
TraceMessage("Debuggee version: Unknown (assuming " + debuggeeVersion + ")");
} else {
TraceMessage("Debuggee version: " + debuggeeVersion);
}
this.debuggeeVersion = debuggeeVersion;
int debuggerVersion;
// The CLR does not provide 4.0 debugger interface for older versions
if (debuggeeVersion.StartsWith("v1") || debuggeeVersion.StartsWith("v2")) {
debuggerVersion = 3; // 2.0 CLR
TraceMessage("Debugger interface version: v2.0");
} else {
debuggerVersion = 4; // 4.0 CLR
TraceMessage("Debugger interface version: v4.0");
}
corDebug = NativeMethods.CreateDebuggingInterfaceFromVersion(debuggerVersion, debuggeeVersion);
TrackedComObjects.Track(corDebug);
managedCallbackSwitch = new ManagedCallbackSwitch(this);
managedCallbackProxy = new ManagedCallbackProxy(this, managedCallbackSwitch);
corDebug.Initialize();
corDebug.SetManagedHandler(managedCallbackProxy);
TraceMessage("ICorDebug initialized");
}
internal void TerminateDebugger()
{
// Mark breakpints as deactivated
foreach (Breakpoint b in this.Breakpoints) {
b.MarkAsDeactivated();
}
TraceMessage("Reset done");
corDebug.Terminate();
TraceMessage("ICorDebug terminated");
int released = TrackedComObjects.ReleaseAll();
TraceMessage("Released " + released + " tracked COM objects");
}
/// <summary>
/// Internal: Used to debug the debugger library.
/// </summary>
public event EventHandler<MessageEventArgs> DebuggerTraceMessage;
protected internal virtual void OnDebuggerTraceMessage(MessageEventArgs e)
{
if (DebuggerTraceMessage != null) {
DebuggerTraceMessage(this, e);
}
}
internal void TraceMessage(string message)
{
System.Diagnostics.Debug.WriteLine("Debugger:" + message);
OnDebuggerTraceMessage(new MessageEventArgs(null, message));
}
public void StartWithoutDebugging(System.Diagnostics.ProcessStartInfo psi)
{
System.Diagnostics.Process process;
process = new System.Diagnostics.Process();
process.StartInfo = psi;
process.Start();
}
internal object ProcessIsBeingCreatedLock = new object();
public Process Start(string filename, string workingDirectory, string arguments)
{
InitDebugger(GetProgramVersion(filename));
lock(ProcessIsBeingCreatedLock) {
Process process = Process.CreateProcess(this, filename, workingDirectory, arguments);
// Expose a race conditon
System.Threading.Thread.Sleep(0);
this.Processes.Add(process);
return process;
}
}
public Process Attach(System.Diagnostics.Process existingProcess)
{
string mainModule = existingProcess.MainModule.FileName;
InitDebugger(GetProgramVersion(mainModule));
ICorDebugProcess corDebugProcess = corDebug.DebugActiveProcess((uint)existingProcess.Id, 0);
// TODO: Can we get the acutal working directory?
Process process = new Process(this, corDebugProcess, Path.GetDirectoryName(mainModule));
this.Processes.Add(process);
return process;
}
public void Detach()
{
// Deactivate breakpoints
foreach (Breakpoint b in this.Breakpoints) {
b.Deactivate();
}
// Detach all processes.
for (int i = 0; i < this.Processes.Count; ++i) {
Process process = this.Processes[i];
if (process == null || process.HasExited)
continue;
process.Detach();
}
}
public bool IsKernelDebuggerEnabled {
get {
string systemStartOptions = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\").GetValue("SystemStartOptions", string.Empty).ToString();
// XP does not have the slash, Vista does have it
systemStartOptions = ("/" + systemStartOptions).ToLower().Replace(" ", " /");
if (systemStartOptions.Contains("/nodebug")) {
// this option overrides the others
return false;
}
if (systemStartOptions.Contains("/debug") ||
systemStartOptions.Contains("/crashdebug") ||
systemStartOptions.Contains("/debugport") ||
systemStartOptions.Contains("/baudrate")) {
return true;
} else {
return false;
}
}
}
/// <summary> Try to load module symbols using the search path defined in the options </summary>
public void ReloadModuleSymbols()
{
foreach(Process process in this.Processes) {
foreach(Module module in process.Modules) {
module.LoadSymbolsFromDisk(process.Options.SymbolsSearchPaths);
}
}
TraceMessage("Reloaded symbols");
}
/// <summary> Reset the just my code status of modules. Use this after changing any stepping options. </summary>
public void ResetJustMyCodeStatus()
{
foreach(Process process in this.Processes) {
foreach(Module module in process.Modules) {
module.ResetJustMyCodeStatus();
}
}
TraceMessage("Just my code reseted");
}
}
[Serializable]
public class DebuggerEventArgs : EventArgs
{
NDebugger debugger;
public NDebugger Debugger {
get {
return debugger;
}
}
public DebuggerEventArgs(NDebugger debugger)
{
this.debugger = debugger;
}
}
[Serializable]
public class MessageEventArgs : ProcessEventArgs
{
int level;
string message;
string category;
public int Level {
get {
return level;
}
}
public string Message {
get {
return message;
}
}
public string Category {
get {
return category;
}
}
public MessageEventArgs(Process process, string message): this(process, 0, message, String.Empty)
{
this.message = message;
}
public MessageEventArgs(Process process, int level, string message, string category): base(process)
{
this.level = level;
this.message = message;
this.category = category;
}
}
}

334
Debugger/Debugger.Core/NRefactory/Ast/ExpressionExtensionMethods.cs

@ -0,0 +1,334 @@ @@ -0,0 +1,334 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Reflection;
using Debugger;
using Debugger.MetaData;
using ICSharpCode.NRefactory.Ast;
using ICSharpCode.NRefactory.PrettyPrinter;
using ICSharpCode.NRefactory.Visitors;
namespace ICSharpCode.NRefactory.Ast
{
public static class ExpressionExtensionMethods
{
public static Value Evaluate(this Expression expression, Process process)
{
return ExpressionEvaluator.Evaluate(expression, process);
}
static M SetStaticType<M>(this M expr, DebugType type) where M: INode
{
expr.UserData = type;
return expr;
}
public static DebugType GetStaticType(this INode expr)
{
return expr.UserData as DebugType;
}
public static Expression Parenthesize(this Expression expr)
{
if (expr is IdentifierExpression ||
expr is MemberReferenceExpression ||
expr is IndexerExpression ||
expr is ParenthesizedExpression ||
expr is PrimitiveExpression)
return expr;
return new ParenthesizedExpression(expr);
}
public static Expression CastTo(this Expression expresion, DebugType castTo)
{
// No need to cast
if (expresion.GetStaticType() == castTo)
return expresion;
if (expresion is PrimitiveExpression) {
object val = ((PrimitiveExpression)expresion).Value;
if (val != null && val.GetType().FullName == castTo.FullName)
return expresion;
}
return new CastExpression(castTo.GetTypeReference(), expresion.Parenthesize(), CastType.Cast);
}
public static Expression GetExpression(this DebugLocalVariableInfo locVar)
{
return new IdentifierExpression(locVar.Name).SetStaticType((DebugType)locVar.LocalType);
}
public static Expression GetExpression(this DebugParameterInfo par)
{
return new IdentifierExpression(par.Name).SetStaticType((DebugType)par.ParameterType);
}
public static UnaryOperatorExpression AppendDereference(this Expression expression)
{
return new UnaryOperatorExpression(new ParenthesizedExpression(expression), UnaryOperatorType.Dereference);
}
public static IndexerExpression AppendIndexer(this Expression expression, params int[] indices)
{
IndexerExpression indexerExpr = new IndexerExpression(Parenthesize(expression), new List<Expression>());
foreach(int index in indices) {
indexerExpr.Indexes.Add(new PrimitiveExpression(index));
}
DebugType staticType = expression.GetStaticType();
if (staticType != null && staticType.IsArray)
indexerExpr.SetStaticType((DebugType)staticType.GetElementType());
if (staticType != null && staticType.FullNameWithoutGenericArguments == typeof(List<>).FullName)
indexerExpr.SetStaticType((DebugType)staticType.GetGenericArguments()[0]);
return indexerExpr;
}
public static Expression AppendMemberReference(this Expression expresion, IDebugMemberInfo memberInfo, params Expression[] args)
{
Expression target;
if (memberInfo.IsStatic) {
target = new TypeReferenceExpression(
memberInfo.DeclaringType.GetTypeReference()
);
} else {
target = expresion.CastTo((DebugType)memberInfo.DeclaringType);
}
if (memberInfo is DebugFieldInfo) {
if (args.Length > 0)
throw new DebuggerException("No arguments expected for a field");
return new MemberReferenceExpression(target, memberInfo.Name).SetStaticType(memberInfo.MemberType);
}
if (memberInfo is MethodInfo) {
return new InvocationExpression(
new MemberReferenceExpression(target, memberInfo.Name),
AddExplicitTypes((MethodInfo)memberInfo, args)
).SetStaticType(memberInfo.MemberType);
}
if (memberInfo is PropertyInfo) {
PropertyInfo propInfo = (PropertyInfo)memberInfo;
if (args.Length > 0) {
if (memberInfo.Name != "Item")
throw new DebuggerException("Arguments expected only for the Item property");
return new IndexerExpression(
target,
AddExplicitTypes(propInfo.GetGetMethod() ?? propInfo.GetSetMethod(), args)
).SetStaticType(memberInfo.MemberType);
} else {
return new MemberReferenceExpression(target, memberInfo.Name).SetStaticType(memberInfo.MemberType);
}
}
throw new DebuggerException("Unknown member type " + memberInfo.GetType().FullName);
}
static List<Expression> AddExplicitTypes(MethodInfo method, Expression[] args)
{
if (args.Length != method.GetParameters().Length)
throw new DebuggerException("Incorrect number of arguments");
List<Expression> typedArgs = new List<Expression>(args.Length);
for(int i = 0; i < args.Length; i++) {
typedArgs.Add(args[i].CastTo((DebugType)method.GetParameters()[i].ParameterType));
}
return typedArgs;
}
public static bool Is<T>(this Type type)
{
return type.FullName == typeof(T).FullName;
}
public static bool CanPromoteTo(this Type type, Type toType)
{
return ((DebugType)type).CanImplicitelyConvertTo(toType);
}
public static string PrettyPrint(this INode code)
{
if (code == null) return string.Empty;
CSharpOutputVisitor csOutVisitor = new CSharpOutputVisitor();
code.AcceptVisitor(csOutVisitor, null);
return csOutVisitor.Text;
}
public static TypeReference GetTypeReference(this Type type)
{
List<int> arrayRanks = new List<int>();
while(type.IsArray) {
// C# uses reverse array order
arrayRanks.Add(type.GetArrayRank() - 1);
type = type.GetElementType();
}
int pointerNest = 0;
while(type.IsPointer) {
pointerNest++;
type = type.GetElementType();
}
if (type.IsArray)
throw new DebuggerException("C# does not support pointers to arrays");
string name = type.Name;
if (name.IndexOf('`') != -1)
name = name.Substring(0, name.IndexOf('`'));
if (!string.IsNullOrEmpty(type.Namespace))
name = type.Namespace + "." + name;
List<Type> genArgs = new List<Type>();
// This inludes the generic arguments of the outter types
genArgs.AddRange(type.GetGenericArguments());
if (type.DeclaringType != null)
genArgs.RemoveRange(0, type.DeclaringType.GetGenericArguments().Length);
List<TypeReference> genTypeRefs = new List<TypeReference>();
foreach(Type genArg in genArgs) {
genTypeRefs.Add(genArg.GetTypeReference());
}
if (type.DeclaringType != null) {
TypeReference outterRef = type.DeclaringType.GetTypeReference();
InnerClassTypeReference innerRef = new InnerClassTypeReference(outterRef, name, genTypeRefs);
innerRef.PointerNestingLevel = pointerNest;
innerRef.RankSpecifier = arrayRanks.ToArray();
return innerRef.SetStaticType((DebugType)type);
} else {
return new TypeReference(name, pointerNest, arrayRanks.ToArray(), genTypeRefs).SetStaticType((DebugType)type);
}
}
/// <summary>
/// Converts tree into nested TypeReference/InnerClassTypeReference.
/// Dotted names are split into separate nodes.
/// It does not normalize generic arguments.
/// </summary>
static TypeReference NormalizeTypeReference(this INode expr)
{
if (expr is IdentifierExpression) {
return new TypeReference(
((IdentifierExpression)expr).Identifier,
((IdentifierExpression)expr).TypeArguments
);
} else if (expr is MemberReferenceExpression) {
TypeReference outter = NormalizeTypeReference(((MemberReferenceExpression)expr).TargetObject);
return new InnerClassTypeReference(
outter,
((MemberReferenceExpression)expr).MemberName,
((MemberReferenceExpression)expr).TypeArguments
);
} else if (expr is TypeReferenceExpression) {
return NormalizeTypeReference(((TypeReferenceExpression)expr).TypeReference);
} else if (expr is InnerClassTypeReference) { // Frist - it is also TypeReference
InnerClassTypeReference typeRef = (InnerClassTypeReference)expr;
string[] names = typeRef.Type.Split('.');
TypeReference newRef = NormalizeTypeReference(typeRef.BaseType);
foreach(string name in names) {
newRef = new InnerClassTypeReference(newRef, name, new List<TypeReference>());
}
newRef.GenericTypes.AddRange(typeRef.GenericTypes);
newRef.PointerNestingLevel = typeRef.PointerNestingLevel;
newRef.RankSpecifier = typeRef.RankSpecifier;
return newRef;
} else if (expr is TypeReference) {
TypeReference typeRef = (TypeReference)expr;
string[] names = typeRef.Type.Split('.');
if (names.Length == 1)
return typeRef;
TypeReference newRef = null;
foreach(string name in names) {
if (newRef == null) {
newRef = new TypeReference(name, new List<TypeReference>());
} else {
newRef = new InnerClassTypeReference(newRef, name, new List<TypeReference>());
}
}
newRef.GenericTypes.AddRange(typeRef.GenericTypes);
newRef.PointerNestingLevel = typeRef.PointerNestingLevel;
newRef.RankSpecifier = typeRef.RankSpecifier;
return newRef;
} else {
throw new EvaluateException(expr, "Type expected. {0} seen.", expr.GetType().FullName);
}
}
static string GetNameWithArgCounts(TypeReference typeRef)
{
string name = typeRef.Type;
if (typeRef.GenericTypes.Count > 0)
name += "`" + typeRef.GenericTypes.Count.ToString();
if (typeRef is InnerClassTypeReference) {
return GetNameWithArgCounts(((InnerClassTypeReference)typeRef).BaseType) + "." + name;
} else {
return name;
}
}
public static DebugType ResolveType(this INode expr, Debugger.AppDomain appDomain)
{
if (expr is TypeReference && expr.GetStaticType() != null)
return expr.GetStaticType();
if (expr is TypeReferenceExpression && ((TypeReferenceExpression)expr).TypeReference.GetStaticType() != null)
return ((TypeReferenceExpression)expr).TypeReference.GetStaticType();
appDomain.Process.TraceMessage("Resolving {0}", expr.PrettyPrint());
TypeReference typeRef = NormalizeTypeReference(expr);
List<TypeReference> genTypeRefs;
if (typeRef is InnerClassTypeReference) {
genTypeRefs = ((InnerClassTypeReference)typeRef).CombineToNormalTypeReference().GenericTypes;
} else {
genTypeRefs = typeRef.GenericTypes;
}
List<DebugType> genArgs = new List<DebugType>();
foreach(TypeReference genTypeRef in genTypeRefs) {
genArgs.Add(ResolveType(genTypeRef, appDomain));
}
return ResolveTypeInternal(typeRef, genArgs.ToArray(), appDomain);
}
/// <summary>
/// For performance this is separate method.
/// 'genArgs' should hold type for each generic parameter in 'typeRef'.
/// </summary>
static DebugType ResolveTypeInternal(TypeReference typeRef, DebugType[] genArgs, Debugger.AppDomain appDomain)
{
DebugType type = null;
// Try to construct non-nested type
// If there are generic types up in the tree, it must be nested type
if (genArgs.Length == typeRef.GenericTypes.Count) {
string name = GetNameWithArgCounts(typeRef);
type = DebugType.CreateFromNameOrNull(appDomain, name, null, genArgs);
}
// Try to construct nested type
if (type == null && typeRef is InnerClassTypeReference) {
DebugType[] outterGenArgs = genArgs;
// Do not pass our generic arguments to outter type
Array.Resize(ref outterGenArgs, genArgs.Length - typeRef.GenericTypes.Count);
DebugType outter = ResolveTypeInternal(((InnerClassTypeReference)typeRef).BaseType, outterGenArgs, appDomain);
string nestedName = typeRef.GenericTypes.Count == 0 ? typeRef.Type : typeRef.Type + "`" + typeRef.GenericTypes.Count;
type = DebugType.CreateFromNameOrNull(appDomain, nestedName, outter, genArgs);
}
if (type == null)
throw new GetValueException("Can not resolve " + typeRef.PrettyPrint());
for(int i = 0; i < typeRef.PointerNestingLevel; i++) {
type = (DebugType)type.MakePointerType();
}
if (typeRef.RankSpecifier != null) {
for(int i = typeRef.RankSpecifier.Length - 1; i >= 0; i--) {
type = (DebugType)type.MakeArrayType(typeRef.RankSpecifier[i] + 1);
}
}
return type;
}
}
}

1015
Debugger/Debugger.Core/NRefactory/Visitors/ExpressionEvaluator.cs

File diff suppressed because it is too large Load Diff

19
Debugger/Debugger.Core/Options.cs

@ -0,0 +1,19 @@ @@ -0,0 +1,19 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
namespace Debugger
{
public class Options
{
public bool EnableJustMyCode = true;
public bool StepOverNoSymbols = true;
public bool StepOverDebuggerAttributes = true;
public bool StepOverAllProperties = false;
public bool StepOverSingleLineProperties = false;
public bool StepOverFieldAccessProperties = true;
public bool Verbose = false;
public string[] SymbolsSearchPaths = new string[0];
public bool SuspendOtherThreads = true;
public bool EnableEditAndContinue = false;
}
}

29
Debugger/Debugger.Core/PauseSession.cs

@ -0,0 +1,29 @@ @@ -0,0 +1,29 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
namespace Debugger
{
/// <summary>
/// Holds information about the state of paused debugger.
/// Expires when when Continue is called on debugger.
/// </summary>
public class PauseSession: DebuggerObject
{
Process process;
PausedReason pausedReason;
public Process Process {
get { return process; }
}
public PausedReason PausedReason {
get { return pausedReason; }
}
public PauseSession(Process process, PausedReason pausedReason)
{
this.process = process;
this.pausedReason = pausedReason;
}
}
}

22
Debugger/Debugger.Core/PausedReason.cs

@ -0,0 +1,22 @@ @@ -0,0 +1,22 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
namespace Debugger
{
public enum PausedReason : int
{
EvalComplete,
StepComplete,
Breakpoint,
Break,
ControlCTrap,
Exception,
ForcedBreak, // Process.Break called
DebuggerError,
CurrentThreadChanged,
CurrentFunctionChanged,
ExceptionIntercepted,
SetIP,
Other
}
}

694
Debugger/Debugger.Core/Process.cs

@ -0,0 +1,694 @@ @@ -0,0 +1,694 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Debugger.Interop.CorDebug;
using Debugger.Interop.CorSym;
using ICSharpCode.NRefactory.Ast;
using ICSharpCode.NRefactory.Visitors;
namespace Debugger
{
internal enum DebuggeeStateAction { Keep, Clear }
/// <summary>
/// Debug Mode Flags.
/// </summary>
public enum DebugModeFlag
{
/// <summary>
/// Run in the same mode as without debugger.
/// </summary>
Default,
/// <summary>
/// Run in forced optimized mode.
/// </summary>
Optimized,
/// <summary>
/// Run in debug mode (easy inspection) but slower.
/// </summary>
Debug,
/// <summary>
/// Run in ENC mode (ENC possible) but even slower than debug
/// </summary>
Enc
}
public class Process: DebuggerObject
{
NDebugger debugger;
ICorDebugProcess corProcess;
ManagedCallback callbackInterface;
EvalCollection activeEvals;
ModuleCollection modules;
ThreadCollection threads;
AppDomainCollection appDomains;
string workingDirectory;
public NDebugger Debugger {
get { return debugger; }
}
internal ICorDebugProcess CorProcess {
get { return corProcess; }
}
public Options Options {
get { return debugger.Options; }
}
public string DebuggeeVersion {
get { return debugger.DebuggeeVersion; }
}
internal ManagedCallback CallbackInterface {
get { return callbackInterface; }
}
public EvalCollection ActiveEvals {
get { return activeEvals; }
}
internal bool Evaluating {
get { return activeEvals.Count > 0; }
}
public ModuleCollection Modules {
get { return modules; }
}
public ThreadCollection Threads {
get { return threads; }
}
public Thread SelectedThread {
get { return this.Threads.Selected; }
set { this.Threads.Selected = value; }
}
public StackFrame SelectedStackFrame {
get {
if (SelectedThread == null) {
return null;
} else {
return SelectedThread.SelectedStackFrame;
}
}
}
public SourcecodeSegment NextStatement {
get {
if (SelectedStackFrame == null || IsRunning) {
return null;
} else {
return SelectedStackFrame.NextStatement;
}
}
}
public bool BreakAtBeginning {
get;
set;
}
public AppDomainCollection AppDomains {
get { return appDomains; }
}
List<Stepper> steppers = new List<Stepper>();
internal List<Stepper> Steppers {
get { return steppers; }
}
public string WorkingDirectory {
get { return workingDirectory; }
}
public static DebugModeFlag DebugMode { get; set; }
internal Process(NDebugger debugger, ICorDebugProcess corProcess, string workingDirectory)
{
this.debugger = debugger;
this.corProcess = corProcess;
this.workingDirectory = workingDirectory;
this.callbackInterface = new ManagedCallback(this);
activeEvals = new EvalCollection(debugger);
modules = new ModuleCollection(debugger);
modules.Added += OnModulesAdded;
threads = new ThreadCollection(debugger);
appDomains = new AppDomainCollection(debugger);
}
static unsafe public Process CreateProcess(NDebugger debugger, string filename, string workingDirectory, string arguments)
{
debugger.TraceMessage("Executing " + filename + " " + arguments);
uint[] processStartupInfo = new uint[17];
processStartupInfo[0] = sizeof(uint) * 17;
uint[] processInfo = new uint[4];
ICorDebugProcess outProcess;
if (workingDirectory == null || workingDirectory == "") {
workingDirectory = System.IO.Path.GetDirectoryName(filename);
}
_SECURITY_ATTRIBUTES secAttr = new _SECURITY_ATTRIBUTES();
secAttr.bInheritHandle = 0;
secAttr.lpSecurityDescriptor = IntPtr.Zero;
secAttr.nLength = (uint)sizeof(_SECURITY_ATTRIBUTES);
fixed (uint* pprocessStartupInfo = processStartupInfo)
fixed (uint* pprocessInfo = processInfo)
outProcess =
debugger.CorDebug.CreateProcess(
filename, // lpApplicationName
// If we do not prepend " ", the first argument migh just get lost
" " + arguments, // lpCommandLine
ref secAttr, // lpProcessAttributes
ref secAttr, // lpThreadAttributes
1,//TRUE // bInheritHandles
0x00000010 /*CREATE_NEW_CONSOLE*/, // dwCreationFlags
IntPtr.Zero, // lpEnvironment
workingDirectory, // lpCurrentDirectory
(uint)pprocessStartupInfo, // lpStartupInfo
(uint)pprocessInfo, // lpProcessInformation,
CorDebugCreateProcessFlags.DEBUG_NO_SPECIAL_OPTIONS // debuggingFlags
);
return new Process(debugger, outProcess, workingDirectory);
}
/// <summary> Fired when System.Diagnostics.Trace.WriteLine() is called in debuged process </summary>
public event EventHandler<MessageEventArgs> LogMessage;
protected internal virtual void OnLogMessage(MessageEventArgs arg)
{
TraceMessage ("Debugger event: OnLogMessage");
if (LogMessage != null) {
LogMessage(this, arg);
}
}
public void TraceMessage(string message, params object[] args)
{
if (args.Length > 0)
message = string.Format(message, args);
System.Diagnostics.Debug.WriteLine("Debugger:" + message);
debugger.OnDebuggerTraceMessage(new MessageEventArgs(this, message));
}
/// <summary> Read the specified amount of memory at the given memory address </summary>
/// <returns> The content of the memory. The amount of the read memory may be less then requested. </returns>
public unsafe byte[] ReadMemory(ulong address, int size)
{
byte[] buffer = new byte[size];
int readCount;
fixed(byte* pBuffer = buffer) {
readCount = (int)corProcess.ReadMemory(address, (uint)size, new IntPtr(pBuffer));
}
if (readCount != size) Array.Resize(ref buffer, readCount);
return buffer;
}
/// <summary> Writes the given buffer at the specified memory address </summary>
/// <returns> The number of bytes written </returns>
public unsafe int WriteMemory(ulong address, byte[] buffer)
{
if (buffer.Length == 0) return 0;
int written;
fixed(byte* pBuffer = buffer) {
written = (int)corProcess.WriteMemory(address, (uint)buffer.Length, new IntPtr(pBuffer));
}
return written;
}
#region Exceptions
bool pauseOnHandledException = false;
public event EventHandler<ExceptionEventArgs> ExceptionThrown;
public bool PauseOnHandledException {
get { return pauseOnHandledException; }
set { pauseOnHandledException = value; }
}
protected internal virtual void OnExceptionThrown(ExceptionEventArgs e)
{
TraceMessage ("Debugger event: OnExceptionThrown()");
if (ExceptionThrown != null) {
ExceptionThrown(this, e);
}
}
#endregion
// State control for the process
internal bool TerminateCommandIssued = false;
internal Queue<Breakpoint> BreakpointHitEventQueue = new Queue<Breakpoint>();
internal Dictionary<INode, TypedValue> ExpressionsCache = new Dictionary<INode, TypedValue>();
#region Events
public event EventHandler<ProcessEventArgs> Paused;
public event EventHandler<ProcessEventArgs> Resumed;
// HACK: public
public virtual void OnPaused()
{
AssertPaused();
// No real purpose - just additional check
if (callbackInterface.IsInCallback) throw new DebuggerException("Can not raise event within callback.");
TraceMessage ("Debugger event: OnPaused()");
if (Paused != null) {
foreach(Delegate d in Paused.GetInvocationList()) {
if (IsRunning) {
TraceMessage ("Skipping OnPaused delegate because process has resumed");
break;
}
if (this.TerminateCommandIssued || this.HasExited) {
TraceMessage ("Skipping OnPaused delegate because process has exited");
break;
}
d.DynamicInvoke(this, new ProcessEventArgs(this));
}
}
}
protected virtual void OnResumed()
{
AssertRunning();
if (callbackInterface.IsInCallback)
throw new DebuggerException("Can not raise event within callback.");
TraceMessage ("Debugger event: OnResumed()");
if (Resumed != null) {
Resumed(this, new ProcessEventArgs(this));
}
}
#endregion
#region PauseSession & DebugeeState
PauseSession pauseSession;
DebuggeeState debuggeeState;
/// <summary>
/// Indentification of the current debugger session. This value changes whenever debugger is continued
/// </summary>
public PauseSession PauseSession {
get { return pauseSession; }
}
/// <summary>
/// Indentification of the state of the debugee. This value changes whenever the state of the debugee significatntly changes
/// </summary>
public DebuggeeState DebuggeeState {
get { return debuggeeState; }
}
/// <summary> Puts the process into a paused state </summary>
internal void NotifyPaused(PausedReason pauseReason)
{
AssertRunning();
pauseSession = new PauseSession(this, pauseReason);
if (debuggeeState == null) {
debuggeeState = new DebuggeeState(this);
}
}
/// <summary> Puts the process into a resumed state </summary>
internal void NotifyResumed(DebuggeeStateAction action)
{
AssertPaused();
pauseSession = null;
if (action == DebuggeeStateAction.Clear) {
if (debuggeeState == null) throw new DebuggerException("Debugee state already cleared");
debuggeeState = null;
this.ExpressionsCache.Clear();
}
}
/// <summary> Sets up the eviroment and raises user events </summary>
internal void RaisePausedEvents()
{
AssertPaused();
DisableAllSteppers();
CheckSelectedStackFrames();
SelectMostRecentStackFrameWithLoadedSymbols();
if (this.PauseSession.PausedReason == PausedReason.Exception) {
ExceptionEventArgs args = new ExceptionEventArgs(this, this.SelectedThread.CurrentException, this.SelectedThread.CurrentExceptionType, this.SelectedThread.CurrentExceptionIsUnhandled);
OnExceptionThrown(args);
// The event could have resumed or killed the process
if (this.IsRunning || this.TerminateCommandIssued || this.HasExited) return;
}
while(BreakpointHitEventQueue.Count > 0) {
Breakpoint breakpoint = BreakpointHitEventQueue.Dequeue();
breakpoint.NotifyHit();
// The event could have resumed or killed the process
if (this.IsRunning || this.TerminateCommandIssued || this.HasExited) return;
}
OnPaused();
// The event could have resumed the process
if (this.IsRunning || this.TerminateCommandIssued || this.HasExited) return;
}
#endregion
internal void AssertPaused()
{
if (IsRunning) {
throw new DebuggerException("Process is not paused.");
}
}
internal void AssertRunning()
{
if (IsPaused) {
throw new DebuggerException("Process is not running.");
}
}
public bool IsRunning {
get { return pauseSession == null; }
}
public bool IsPaused {
get { return !IsRunning; }
}
bool hasExited = false;
public event EventHandler Exited;
public bool HasExited {
get {
return hasExited;
}
}
internal void NotifyHasExited()
{
if(!hasExited) {
hasExited = true;
if (Exited != null) {
Exited(this, new ProcessEventArgs(this));
}
// Expire pause seesion first
if (IsPaused) {
NotifyResumed(DebuggeeStateAction.Clear);
}
debugger.Processes.Remove(this);
}
}
public void Break()
{
AssertRunning();
corProcess.Stop(uint.MaxValue); // Infinite; ignored anyway
NotifyPaused(PausedReason.ForcedBreak);
RaisePausedEvents();
}
public void Detach()
{
if (IsRunning) {
corProcess.Stop(uint.MaxValue);
NotifyPaused(PausedReason.ForcedBreak);
}
// This is necessary for detach
foreach(Stepper s in this.Steppers) {
if (s.CorStepper.IsActive() == 1) {
s.CorStepper.Deactivate();
}
}
this.Steppers.Clear();
corProcess.Detach();
// modules
foreach(Module m in this.Modules)
{
m.Dispose();
}
this.modules.Clear();
// threads
this.threads.Clear();
NotifyHasExited();
}
public void Continue()
{
AsyncContinue();
WaitForPause();
}
internal Thread[] UnsuspendedThreads {
get {
List<Thread> unsuspendedThreads = new List<Thread>(this.Threads.Count);
foreach(Thread t in this.Threads) {
if (!t.Suspended)
unsuspendedThreads.Add(t);
}
return unsuspendedThreads.ToArray();
}
}
/// <summary>
/// Resume execution and run all threads not marked by the user as susspended.
/// </summary>
public void AsyncContinue()
{
AsyncContinue(DebuggeeStateAction.Clear, this.UnsuspendedThreads, CorDebugThreadState.THREAD_RUN);
}
internal CorDebugThreadState NewThreadState = CorDebugThreadState.THREAD_RUN;
/// <param name="threadsToRun"> Null to keep current setting </param>
/// <param name="newThreadState"> What happens to created threads. Null to keep current setting </param>
internal void AsyncContinue(DebuggeeStateAction action, Thread[] threadsToRun, CorDebugThreadState? newThreadState)
{
AssertPaused();
if (threadsToRun != null) {
// corProcess.SetAllThreadsDebugState(CorDebugThreadState.THREAD_SUSPEND, null);
// Note: There is unreported thread, stopping it prevents the debugee from exiting
// It is not corProcess.GetHelperThreadID
// ICorDebugThread[] ts = new ICorDebugThread[corProcess.EnumerateThreads().GetCount()];
// corProcess.EnumerateThreads().Next((uint)ts.Length, ts);
foreach(Thread t in this.Threads) {
CorDebugThreadState state = Array.IndexOf(threadsToRun, t) == -1 ? CorDebugThreadState.THREAD_SUSPEND : CorDebugThreadState.THREAD_RUN;
try {
t.CorThread.SetDebugState(state);
} catch (COMException e) {
// The state of the thread is invalid. (Exception from HRESULT: 0x8013132D)
// It can happen for example when thread has not started yet
if ((uint)e.ErrorCode == 0x8013132D) {
// TraceMessage("Can not suspend thread - The state of the thread is invalid. Thread ID = " + t.CorThread.GetID());
} else {
throw;
}
}
}
}
if (newThreadState != null) {
this.NewThreadState = newThreadState.Value;
}
NotifyResumed(action);
corProcess.Continue(0);
if (this.Options.Verbose) {
this.TraceMessage("Continue");
}
if (action == DebuggeeStateAction.Clear) {
OnResumed();
}
}
/// <summary> Terminates the execution of the process </summary>
public void Terminate()
{
AsyncTerminate();
// Wait until ExitProcess callback is received
WaitForExit();
}
/// <summary> Terminates the execution of the process </summary>
public void AsyncTerminate()
{
// Resume stoped tread
if (this.IsPaused) {
// We might get more callbacks so we should maintain consistent sate
//AsyncContinue(); // Continue the process to get remaining callbacks
}
// Expose race condition - drain callback queue
System.Threading.Thread.Sleep(0);
// Stop&terminate - both must be called
corProcess.Stop(uint.MaxValue);
corProcess.Terminate(0);
this.TerminateCommandIssued = true;
// Do not mark the process as exited
// This is done once ExitProcess callback is received
}
void SelectSomeThread()
{
if (this.SelectedThread != null && !this.SelectedThread.IsInValidState) {
this.SelectedThread = null;
}
if (this.SelectedThread == null) {
foreach(Thread thread in this.Threads) {
if (thread.IsInValidState) {
this.SelectedThread = thread;
break;
}
}
}
}
internal void CheckSelectedStackFrames()
{
foreach(Thread thread in this.Threads) {
if (thread.IsInValidState) {
if (thread.SelectedStackFrame != null && thread.SelectedStackFrame.IsInvalid) {
thread.SelectedStackFrame = null;
}
} else {
thread.SelectedStackFrame = null;
}
}
}
internal void SelectMostRecentStackFrameWithLoadedSymbols()
{
SelectSomeThread();
if (this.SelectedThread != null) {
this.SelectedThread.SelectedStackFrame = null;
foreach (StackFrame stackFrame in this.SelectedThread.Callstack) {
if (stackFrame.HasSymbols) {
if (this.Options.StepOverDebuggerAttributes && stackFrame.MethodInfo.IsNonUserCode)
continue;
this.SelectedThread.SelectedStackFrame = stackFrame;
break;
}
}
}
}
internal Stepper GetStepper(ICorDebugStepper corStepper)
{
foreach(Stepper stepper in this.Steppers) {
if (stepper.IsCorStepper(corStepper)) {
return stepper;
}
}
throw new DebuggerException("Stepper is not in collection");
}
internal void DisableAllSteppers()
{
foreach(Thread thread in this.Threads) {
thread.CurrentStepIn = null;
}
foreach(Stepper stepper in this.Steppers) {
stepper.Ignore = true;
}
}
/// <summary>
/// Waits until the debugger pauses unless it is already paused.
/// Use PausedReason to find out why it paused.
/// </summary>
public void WaitForPause()
{
while(this.IsRunning && !this.HasExited) {
debugger.MTA2STA.WaitForCall();
debugger.MTA2STA.PerformAllCalls();
}
if (this.HasExited) throw new ProcessExitedException();
}
public void WaitForPause(TimeSpan timeout)
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
while(this.IsRunning && !this.HasExited) {
TimeSpan timeLeft = timeout - watch.Elapsed;
if (timeLeft <= TimeSpan.FromMilliseconds(10)) break;
//this.TraceMessage("Time left: " + timeLeft.TotalMilliseconds);
debugger.MTA2STA.WaitForCall(timeLeft);
debugger.MTA2STA.PerformAllCalls();
}
if (this.HasExited) throw new ProcessExitedException();
}
/// <summary>
/// Waits until the precesses exits.
/// </summary>
public void WaitForExit()
{
while(!this.HasExited) {
debugger.MTA2STA.WaitForCall();
debugger.MTA2STA.PerformAllCalls();
}
}
#region Break at begining
private void OnModulesAdded(object sender, CollectionItemEventArgs<Module> e)
{
if (BreakAtBeginning) {
if (e.Item.SymReader == null) return; // No symbols
try {
// create a BP at entry point
uint entryPoint = e.Item.SymReader.GetUserEntryPoint();
if (entryPoint == 0) return; // no EP
var mainFunction = e.Item.CorModule.GetFunctionFromToken(entryPoint);
var corBreakpoint = mainFunction.CreateBreakpoint();
corBreakpoint.Activate(1);
// create a SD BP
var breakpoint = new Breakpoint(this.debugger, corBreakpoint);
this.debugger.Breakpoints.Add(breakpoint);
breakpoint.Hit += delegate {
if (breakpoint != null)
breakpoint.Remove();
breakpoint = null;
};
} catch {
// the app does not have an entry point - COM exception
}
BreakAtBeginning = false;
}
}
#endregion
}
}

34
Debugger/Debugger.Core/ProcessCollection.cs

@ -0,0 +1,34 @@ @@ -0,0 +1,34 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using Debugger.Interop.CorDebug;
namespace Debugger
{
public class ProcessCollection: CollectionWithEvents<Process>
{
public ProcessCollection(NDebugger debugger): base(debugger) {}
internal Process this[ICorDebugProcess corProcess] {
get {
foreach (Process process in this) {
if (process.CorProcess == corProcess) {
return process;
}
}
return null;
}
}
protected override void OnRemoved(Process item)
{
base.OnRemoved(item);
if (this.Count == 0) {
// Exit callback and then terminate the debugger
this.Debugger.MTA2STA.AsyncCall( delegate { this.Debugger.TerminateDebugger(); } );
}
}
}
}

22
Debugger/Debugger.Core/ProcessEventArgs.cs

@ -0,0 +1,22 @@ @@ -0,0 +1,22 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
namespace Debugger
{
[Serializable]
public class ProcessEventArgs: DebuggerEventArgs
{
Process process;
public Process Process {
get { return process; }
}
public ProcessEventArgs(Process process): base(process == null ? null : process.Debugger)
{
this.process = process;
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save