mirror of https://github.com/icsharpcode/ILSpy.git
77 changed files with 2550 additions and 1410 deletions
@ -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 MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.Threading; |
||||
using Mono.Cecil; |
||||
|
||||
namespace Decompiler |
||||
{ |
||||
public class DecompilerContext |
||||
{ |
||||
public CancellationToken CancellationToken; |
||||
public TypeDefinition CurrentType; |
||||
public MethodDefinition CurrentMethod; |
||||
|
||||
public DecompilerContext Clone() |
||||
{ |
||||
return (DecompilerContext)MemberwiseClone(); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,158 @@
@@ -0,0 +1,158 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Linq; |
||||
using Mono.Cecil; |
||||
|
||||
namespace Decompiler |
||||
{ |
||||
public class NameVariables |
||||
{ |
||||
static readonly Dictionary<string, string> typeNameToVariableNameDict = new Dictionary<string, string> { |
||||
{ "System.Boolean", "flag" }, |
||||
{ "System.Byte", "b" }, |
||||
{ "System.SByte", "b" }, |
||||
{ "System.Int16", "num" }, |
||||
{ "System.Int32", "num" }, |
||||
{ "System.Int64", "num" }, |
||||
{ "System.UInt16", "num" }, |
||||
{ "System.UInt32", "num" }, |
||||
{ "System.UInt64", "num" }, |
||||
{ "System.Single", "num" }, |
||||
{ "System.Double", "num" }, |
||||
{ "System.Decimal", "num" }, |
||||
{ "System.String", "text" }, |
||||
{ "System.Object", "obj" }, |
||||
}; |
||||
|
||||
|
||||
public static void AssignNamesToVariables(IEnumerable<string> existingNames, IEnumerable<ILVariable> variables, ILBlock methodBody) |
||||
{ |
||||
NameVariables nv = new NameVariables(); |
||||
nv.AddExistingNames(existingNames); |
||||
foreach (ILVariable varDef in variables) { |
||||
nv.AssignNameToVariable(varDef, methodBody.GetSelfAndChildrenRecursive<ILExpression>()); |
||||
} |
||||
} |
||||
|
||||
Dictionary<string, int> typeNames = new Dictionary<string, int>(); |
||||
|
||||
void AddExistingNames(IEnumerable<string> existingNames) |
||||
{ |
||||
foreach (string name in existingNames) { |
||||
if (string.IsNullOrEmpty(name)) |
||||
continue; |
||||
// First, identify whether the name already ends with a number:
|
||||
int pos = name.Length; |
||||
while (pos > 0 && name[pos-1] >= '0' && name[pos-1] <= '9') |
||||
pos--; |
||||
if (pos < name.Length) { |
||||
int number; |
||||
if (int.TryParse(name.Substring(pos), out number)) { |
||||
string nameWithoutDigits = name.Substring(0, pos); |
||||
int existingNumber; |
||||
if (typeNames.TryGetValue(nameWithoutDigits, out existingNumber)) { |
||||
typeNames[nameWithoutDigits] = Math.Max(number, existingNumber); |
||||
} else { |
||||
typeNames.Add(nameWithoutDigits, number); |
||||
} |
||||
continue; |
||||
} |
||||
} |
||||
if (!typeNames.ContainsKey(name)) |
||||
typeNames.Add(name, 1); |
||||
} |
||||
} |
||||
|
||||
void AssignNameToVariable(ILVariable varDef, IEnumerable<ILExpression> allExpressions) |
||||
{ |
||||
string proposedName = null; |
||||
foreach (ILExpression expr in allExpressions) { |
||||
if (expr.Operand != varDef) |
||||
continue; |
||||
if (expr.Code == ILCode.Stloc) { |
||||
proposedName = GetNameFromExpression(expr.Arguments.Single()); |
||||
} |
||||
if (proposedName != null) |
||||
break; |
||||
} |
||||
if (proposedName == null) |
||||
proposedName = GetNameByType(varDef.Type); |
||||
|
||||
if (!typeNames.ContainsKey(proposedName)) { |
||||
typeNames.Add(proposedName, 0); |
||||
} |
||||
int count = ++typeNames[proposedName]; |
||||
if (count > 1) { |
||||
varDef.Name = proposedName + count.ToString(); |
||||
} else { |
||||
varDef.Name = proposedName; |
||||
} |
||||
} |
||||
|
||||
static string GetNameFromExpression(ILExpression expr) |
||||
{ |
||||
switch (expr.Code) { |
||||
case ILCode.Ldfld: |
||||
// Use the field name only if it's not a field on this (avoid confusion between local variables and fields)
|
||||
if (!(expr.Arguments[0].Code == ILCode.Ldloc && ((ParameterDefinition)expr.Arguments[0].Operand).Index < 0)) |
||||
return ((FieldReference)expr.Operand).Name; |
||||
break; |
||||
case ILCode.Ldsfld: |
||||
return ((FieldReference)expr.Operand).Name; |
||||
case ILCode.Call: |
||||
case ILCode.Callvirt: |
||||
MethodReference mr = (MethodReference)expr.Operand; |
||||
if (mr.Name.StartsWith("get_", StringComparison.Ordinal)) |
||||
return CleanUpVariableName(mr.Name.Substring(4)); |
||||
else if (mr.Name.StartsWith("Get", StringComparison.Ordinal) && mr.Name.Length >= 4 && char.IsUpper(mr.Name[3])) |
||||
return CleanUpVariableName(mr.Name.Substring(3)); |
||||
break; |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
string GetNameByType(TypeReference type) |
||||
{ |
||||
GenericInstanceType git = type as GenericInstanceType; |
||||
if (git != null && git.ElementType.FullName == "System.Nullable`1" && git.GenericArguments.Count == 1) { |
||||
type = ((GenericInstanceType)type).GenericArguments[0]; |
||||
} |
||||
|
||||
if (type.FullName == "System.Int32") { |
||||
// try i,j,k, etc.
|
||||
for (char c = 'i'; c <= 'n'; c++) { |
||||
if (!typeNames.ContainsKey(c.ToString())) |
||||
return c.ToString(); |
||||
} |
||||
} |
||||
string name; |
||||
if (type.IsArray) { |
||||
name = "array"; |
||||
} else if (type.IsPointer) { |
||||
name = "ptr"; |
||||
} else if (!typeNameToVariableNameDict.TryGetValue(type.FullName, out name)) { |
||||
name = type.Name; |
||||
// remove the 'I' for interfaces
|
||||
if (name.Length >= 3 && name[0] == 'I' && char.IsUpper(name[1]) && char.IsLower(name[2])) |
||||
name = name.Substring(1); |
||||
name = CleanUpVariableName(name); |
||||
} |
||||
return name; |
||||
} |
||||
|
||||
static string CleanUpVariableName(string name) |
||||
{ |
||||
// remove the backtick (generics)
|
||||
int pos = name.IndexOf('`'); |
||||
if (pos >= 0) |
||||
name = name.Substring(0, pos); |
||||
if (name.Length == 0) |
||||
return "obj"; |
||||
else |
||||
return char.ToLower(name[0]) + name.Substring(1); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,69 @@
@@ -0,0 +1,69 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.Diagnostics; |
||||
using ICSharpCode.NRefactory.CSharp; |
||||
using Mono.Cecil; |
||||
|
||||
namespace Decompiler.Transforms |
||||
{ |
||||
/// <summary>
|
||||
/// Base class for AST visitors that need the current type/method context info.
|
||||
/// </summary>
|
||||
public abstract class ContextTrackingVisitor : DepthFirstAstVisitor<object, object> |
||||
{ |
||||
protected readonly DecompilerContext context; |
||||
|
||||
protected ContextTrackingVisitor(DecompilerContext context) |
||||
{ |
||||
if (context == null) |
||||
throw new ArgumentNullException("context"); |
||||
this.context = context; |
||||
} |
||||
|
||||
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) |
||||
{ |
||||
TypeDefinition oldType = context.CurrentType; |
||||
try { |
||||
context.CurrentType = typeDeclaration.Annotation<TypeDefinition>(); |
||||
return base.VisitTypeDeclaration(typeDeclaration, data); |
||||
} finally { |
||||
context.CurrentType = oldType; |
||||
} |
||||
} |
||||
|
||||
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data) |
||||
{ |
||||
Debug.Assert(context.CurrentMethod == null); |
||||
try { |
||||
context.CurrentMethod = methodDeclaration.Annotation<MethodDefinition>(); |
||||
return base.VisitMethodDeclaration(methodDeclaration, data); |
||||
} finally { |
||||
context.CurrentMethod = null; |
||||
} |
||||
} |
||||
|
||||
public override object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data) |
||||
{ |
||||
Debug.Assert(context.CurrentMethod == null); |
||||
try { |
||||
context.CurrentMethod = constructorDeclaration.Annotation<MethodDefinition>(); |
||||
return base.VisitConstructorDeclaration(constructorDeclaration, data); |
||||
} finally { |
||||
context.CurrentMethod = null; |
||||
} |
||||
} |
||||
|
||||
public override object VisitAccessor(Accessor accessor, object data) |
||||
{ |
||||
Debug.Assert(context.CurrentMethod == null); |
||||
try { |
||||
context.CurrentMethod = accessor.Annotation<MethodDefinition>(); |
||||
return base.VisitAccessor(accessor, data); |
||||
} finally { |
||||
context.CurrentMethod = null; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,424 @@
@@ -0,0 +1,424 @@
|
||||
// Author:
|
||||
// Jb Evain (jbevain@gmail.com)
|
||||
//
|
||||
// Copyright (c) 2008 - 2010 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 System; |
||||
using Mono.Cecil; |
||||
using Mono.Cecil.Cil; |
||||
|
||||
namespace Decompiler |
||||
{ |
||||
public enum ILCode |
||||
{ |
||||
// For convenience, the start is exactly identical to Mono.Cecil.Cil.Code
|
||||
// The macro instructions should never be used and are therefore prepended by __
|
||||
Nop, |
||||
Break, |
||||
__Ldarg_0, |
||||
__Ldarg_1, |
||||
__Ldarg_2, |
||||
__Ldarg_3, |
||||
__Ldloc_0, |
||||
__Ldloc_1, |
||||
__Ldloc_2, |
||||
__Ldloc_3, |
||||
__Stloc_0, |
||||
__Stloc_1, |
||||
__Stloc_2, |
||||
__Stloc_3, |
||||
__Ldarg_S, |
||||
__Ldarga_S, |
||||
__Starg_S, |
||||
__Ldloc_S, |
||||
__Ldloca_S, |
||||
__Stloc_S, |
||||
Ldnull, |
||||
__Ldc_I4_M1, |
||||
__Ldc_I4_0, |
||||
__Ldc_I4_1, |
||||
__Ldc_I4_2, |
||||
__Ldc_I4_3, |
||||
__Ldc_I4_4, |
||||
__Ldc_I4_5, |
||||
__Ldc_I4_6, |
||||
__Ldc_I4_7, |
||||
__Ldc_I4_8, |
||||
__Ldc_I4_S, |
||||
Ldc_I4, |
||||
Ldc_I8, |
||||
Ldc_R4, |
||||
Ldc_R8, |
||||
Dup, |
||||
Pop, |
||||
Jmp, |
||||
Call, |
||||
Calli, |
||||
Ret, |
||||
__Br_S, |
||||
__Brfalse_S, |
||||
__Brtrue_S, |
||||
__Beq_S, |
||||
__Bge_S, |
||||
__Bgt_S, |
||||
__Ble_S, |
||||
__Blt_S, |
||||
__Bne_Un_S, |
||||
__Bge_Un_S, |
||||
__Bgt_Un_S, |
||||
__Ble_Un_S, |
||||
__Blt_Un_S, |
||||
Br, |
||||
Brfalse, |
||||
Brtrue, |
||||
Beq, |
||||
Bge, |
||||
Bgt, |
||||
Ble, |
||||
Blt, |
||||
Bne_Un, |
||||
Bge_Un, |
||||
Bgt_Un, |
||||
Ble_Un, |
||||
Blt_Un, |
||||
Switch, |
||||
Ldind_I1, |
||||
Ldind_U1, |
||||
Ldind_I2, |
||||
Ldind_U2, |
||||
Ldind_I4, |
||||
Ldind_U4, |
||||
Ldind_I8, |
||||
Ldind_I, |
||||
Ldind_R4, |
||||
Ldind_R8, |
||||
Ldind_Ref, |
||||
Stind_Ref, |
||||
Stind_I1, |
||||
Stind_I2, |
||||
Stind_I4, |
||||
Stind_I8, |
||||
Stind_R4, |
||||
Stind_R8, |
||||
Add, |
||||
Sub, |
||||
Mul, |
||||
Div, |
||||
Div_Un, |
||||
Rem, |
||||
Rem_Un, |
||||
And, |
||||
Or, |
||||
Xor, |
||||
Shl, |
||||
Shr, |
||||
Shr_Un, |
||||
Neg, |
||||
Not, |
||||
Conv_I1, |
||||
Conv_I2, |
||||
Conv_I4, |
||||
Conv_I8, |
||||
Conv_R4, |
||||
Conv_R8, |
||||
Conv_U4, |
||||
Conv_U8, |
||||
Callvirt, |
||||
Cpobj, |
||||
Ldobj, |
||||
Ldstr, |
||||
Newobj, |
||||
Castclass, |
||||
Isinst, |
||||
Conv_R_Un, |
||||
Unbox, |
||||
Throw, |
||||
Ldfld, |
||||
Ldflda, |
||||
Stfld, |
||||
Ldsfld, |
||||
Ldsflda, |
||||
Stsfld, |
||||
Stobj, |
||||
Conv_Ovf_I1_Un, |
||||
Conv_Ovf_I2_Un, |
||||
Conv_Ovf_I4_Un, |
||||
Conv_Ovf_I8_Un, |
||||
Conv_Ovf_U1_Un, |
||||
Conv_Ovf_U2_Un, |
||||
Conv_Ovf_U4_Un, |
||||
Conv_Ovf_U8_Un, |
||||
Conv_Ovf_I_Un, |
||||
Conv_Ovf_U_Un, |
||||
Box, |
||||
Newarr, |
||||
Ldlen, |
||||
Ldelema, |
||||
Ldelem_I1, |
||||
Ldelem_U1, |
||||
Ldelem_I2, |
||||
Ldelem_U2, |
||||
Ldelem_I4, |
||||
Ldelem_U4, |
||||
Ldelem_I8, |
||||
Ldelem_I, |
||||
Ldelem_R4, |
||||
Ldelem_R8, |
||||
Ldelem_Ref, |
||||
Stelem_I, |
||||
Stelem_I1, |
||||
Stelem_I2, |
||||
Stelem_I4, |
||||
Stelem_I8, |
||||
Stelem_R4, |
||||
Stelem_R8, |
||||
Stelem_Ref, |
||||
Ldelem_Any, |
||||
Stelem_Any, |
||||
Unbox_Any, |
||||
Conv_Ovf_I1, |
||||
Conv_Ovf_U1, |
||||
Conv_Ovf_I2, |
||||
Conv_Ovf_U2, |
||||
Conv_Ovf_I4, |
||||
Conv_Ovf_U4, |
||||
Conv_Ovf_I8, |
||||
Conv_Ovf_U8, |
||||
Refanyval, |
||||
Ckfinite, |
||||
Mkrefany, |
||||
Ldtoken, |
||||
Conv_U2, |
||||
Conv_U1, |
||||
Conv_I, |
||||
Conv_Ovf_I, |
||||
Conv_Ovf_U, |
||||
Add_Ovf, |
||||
Add_Ovf_Un, |
||||
Mul_Ovf, |
||||
Mul_Ovf_Un, |
||||
Sub_Ovf, |
||||
Sub_Ovf_Un, |
||||
Endfinally, |
||||
Leave, |
||||
__Leave_S, |
||||
Stind_I, |
||||
Conv_U, |
||||
Arglist, |
||||
Ceq, |
||||
Cgt, |
||||
Cgt_Un, |
||||
Clt, |
||||
Clt_Un, |
||||
Ldftn, |
||||
Ldvirtftn, |
||||
Ldarg, |
||||
Ldarga, |
||||
Starg, |
||||
Ldloc, |
||||
Ldloca, |
||||
Stloc, |
||||
Localloc, |
||||
Endfilter, |
||||
Unaligned, |
||||
Volatile, |
||||
Tail, |
||||
Initobj, |
||||
Constrained, |
||||
Cpblk, |
||||
Initblk, |
||||
No, |
||||
Rethrow, |
||||
Sizeof, |
||||
Refanytype, |
||||
Readonly, |
||||
|
||||
// Virtual codes - defined for convenience
|
||||
Ldexception, // Operand holds the CatchType for catch handler, null for filter
|
||||
} |
||||
|
||||
public static class ILCodeUtil |
||||
{ |
||||
public static string GetName(this ILCode code) |
||||
{ |
||||
return code.ToString().ToLowerInvariant().Replace('_','.'); |
||||
} |
||||
|
||||
public static bool CanFallThough(this ILCode code) |
||||
{ |
||||
switch(code) { |
||||
case ILCode.Br: |
||||
case ILCode.__Br_S: |
||||
case ILCode.Leave: |
||||
case ILCode.__Leave_S: |
||||
case ILCode.Ret: |
||||
case ILCode.Endfilter: |
||||
case ILCode.Endfinally: |
||||
case ILCode.Throw: |
||||
case ILCode.Rethrow: |
||||
return false; |
||||
default: |
||||
return true; |
||||
} |
||||
} |
||||
|
||||
public static int? GetPopCount(this Instruction inst) |
||||
{ |
||||
switch(inst.OpCode.StackBehaviourPop) { |
||||
case StackBehaviour.Pop0: return 0; |
||||
case StackBehaviour.Pop1: return 1; |
||||
case StackBehaviour.Popi: return 1; |
||||
case StackBehaviour.Popref: return 1; |
||||
case StackBehaviour.Pop1_pop1: return 2; |
||||
case StackBehaviour.Popi_pop1: return 2; |
||||
case StackBehaviour.Popi_popi: return 2; |
||||
case StackBehaviour.Popi_popi8: return 2; |
||||
case StackBehaviour.Popi_popr4: return 2; |
||||
case StackBehaviour.Popi_popr8: return 2; |
||||
case StackBehaviour.Popref_pop1: return 2; |
||||
case StackBehaviour.Popref_popi: return 2; |
||||
case StackBehaviour.Popi_popi_popi: return 3; |
||||
case StackBehaviour.Popref_popi_popi: return 3; |
||||
case StackBehaviour.Popref_popi_popi8: return 3; |
||||
case StackBehaviour.Popref_popi_popr4: return 3; |
||||
case StackBehaviour.Popref_popi_popr8: return 3; |
||||
case StackBehaviour.Popref_popi_popref: return 3; |
||||
case StackBehaviour.PopAll: return null; |
||||
case StackBehaviour.Varpop: |
||||
switch(inst.OpCode.Code) { |
||||
case Code.Call: |
||||
case Code.Callvirt: |
||||
MethodReference cecilMethod = ((MethodReference)inst.Operand); |
||||
if (cecilMethod.HasThis) { |
||||
return cecilMethod.Parameters.Count + 1 /* this */; |
||||
} else { |
||||
return cecilMethod.Parameters.Count; |
||||
} |
||||
case Code.Calli: throw new NotImplementedException(); |
||||
case Code.Ret: return null; |
||||
case Code.Newobj: |
||||
MethodReference ctorMethod = ((MethodReference)inst.Operand); |
||||
return ctorMethod.Parameters.Count; |
||||
default: throw new Exception("Unknown Varpop opcode"); |
||||
} |
||||
default: throw new Exception("Unknown pop behaviour: " + inst.OpCode.StackBehaviourPop); |
||||
} |
||||
} |
||||
|
||||
public static int GetPushCount(this Instruction inst) |
||||
{ |
||||
switch(inst.OpCode.StackBehaviourPush) { |
||||
case StackBehaviour.Push0: return 0; |
||||
case StackBehaviour.Push1: return 1; |
||||
case StackBehaviour.Push1_push1: return 2; |
||||
case StackBehaviour.Pushi: return 1; |
||||
case StackBehaviour.Pushi8: return 1; |
||||
case StackBehaviour.Pushr4: return 1; |
||||
case StackBehaviour.Pushr8: return 1; |
||||
case StackBehaviour.Pushref: return 1; |
||||
case StackBehaviour.Varpush: // Happens only for calls
|
||||
switch(inst.OpCode.Code) { |
||||
case Code.Call: |
||||
case Code.Callvirt: |
||||
MethodReference cecilMethod = ((MethodReference)inst.Operand); |
||||
if (cecilMethod.ReturnType.FullName == "System.Void") { |
||||
return 0; |
||||
} else { |
||||
return 1; |
||||
} |
||||
case Code.Calli: throw new NotImplementedException(); |
||||
default: throw new Exception("Unknown Varpush opcode"); |
||||
} |
||||
default: throw new Exception("Unknown push behaviour: " + inst.OpCode.StackBehaviourPush); |
||||
} |
||||
} |
||||
|
||||
public static void ExpandMacro(ref ILCode code, ref object operand, MethodBody methodBody) |
||||
{ |
||||
switch (code) { |
||||
case ILCode.__Ldarg_0: code = ILCode.Ldarg; operand = methodBody.GetParameter(0); break; |
||||
case ILCode.__Ldarg_1: code = ILCode.Ldarg; operand = methodBody.GetParameter(1); break; |
||||
case ILCode.__Ldarg_2: code = ILCode.Ldarg; operand = methodBody.GetParameter(2); break; |
||||
case ILCode.__Ldarg_3: code = ILCode.Ldarg; operand = methodBody.GetParameter(3); break; |
||||
case ILCode.__Ldloc_0: code = ILCode.Ldloc; operand = methodBody.Variables[0]; break; |
||||
case ILCode.__Ldloc_1: code = ILCode.Ldloc; operand = methodBody.Variables[1]; break; |
||||
case ILCode.__Ldloc_2: code = ILCode.Ldloc; operand = methodBody.Variables[2]; break; |
||||
case ILCode.__Ldloc_3: code = ILCode.Ldloc; operand = methodBody.Variables[3]; break; |
||||
case ILCode.__Stloc_0: code = ILCode.Stloc; operand = methodBody.Variables[0]; break; |
||||
case ILCode.__Stloc_1: code = ILCode.Stloc; operand = methodBody.Variables[1]; break; |
||||
case ILCode.__Stloc_2: code = ILCode.Stloc; operand = methodBody.Variables[2]; break; |
||||
case ILCode.__Stloc_3: code = ILCode.Stloc; operand = methodBody.Variables[3]; break; |
||||
case ILCode.__Ldarg_S: code = ILCode.Ldarg; break; |
||||
case ILCode.__Ldarga_S: code = ILCode.Ldarga; break; |
||||
case ILCode.__Starg_S: code = ILCode.Starg; break; |
||||
case ILCode.__Ldloc_S: code = ILCode.Ldloc; break; |
||||
case ILCode.__Ldloca_S: code = ILCode.Ldloca; break; |
||||
case ILCode.__Stloc_S: code = ILCode.Stloc; break; |
||||
case ILCode.__Ldc_I4_M1: code = ILCode.Ldc_I4; operand = -1; break; |
||||
case ILCode.__Ldc_I4_0: code = ILCode.Ldc_I4; operand = 0; break; |
||||
case ILCode.__Ldc_I4_1: code = ILCode.Ldc_I4; operand = 1; break; |
||||
case ILCode.__Ldc_I4_2: code = ILCode.Ldc_I4; operand = 2; break; |
||||
case ILCode.__Ldc_I4_3: code = ILCode.Ldc_I4; operand = 3; break; |
||||
case ILCode.__Ldc_I4_4: code = ILCode.Ldc_I4; operand = 4; break; |
||||
case ILCode.__Ldc_I4_5: code = ILCode.Ldc_I4; operand = 5; break; |
||||
case ILCode.__Ldc_I4_6: code = ILCode.Ldc_I4; operand = 6; break; |
||||
case ILCode.__Ldc_I4_7: code = ILCode.Ldc_I4; operand = 7; break; |
||||
case ILCode.__Ldc_I4_8: code = ILCode.Ldc_I4; operand = 8; break; |
||||
case ILCode.__Ldc_I4_S: code = ILCode.Ldc_I4; operand = (int) (sbyte) operand; break; |
||||
case ILCode.__Br_S: code = ILCode.Br; break; |
||||
case ILCode.__Brfalse_S: code = ILCode.Brfalse; break; |
||||
case ILCode.__Brtrue_S: code = ILCode.Brtrue; break; |
||||
case ILCode.__Beq_S: code = ILCode.Beq; break; |
||||
case ILCode.__Bge_S: code = ILCode.Bge; break; |
||||
case ILCode.__Bgt_S: code = ILCode.Bgt; break; |
||||
case ILCode.__Ble_S: code = ILCode.Ble; break; |
||||
case ILCode.__Blt_S: code = ILCode.Blt; break; |
||||
case ILCode.__Bne_Un_S: code = ILCode.Bne_Un; break; |
||||
case ILCode.__Bge_Un_S: code = ILCode.Bge_Un; break; |
||||
case ILCode.__Bgt_Un_S: code = ILCode.Bgt_Un; break; |
||||
case ILCode.__Ble_Un_S: code = ILCode.Ble_Un; break; |
||||
case ILCode.__Blt_Un_S: code = ILCode.Blt_Un; break; |
||||
case ILCode.__Leave_S: code = ILCode.Leave; break; |
||||
} |
||||
} |
||||
|
||||
public static ParameterDefinition GetParameter (this MethodBody self, int index) |
||||
{ |
||||
var method = self.Method; |
||||
|
||||
if (method.HasThis) { |
||||
if (index == 0) |
||||
return self.ThisParameter; |
||||
|
||||
index--; |
||||
} |
||||
|
||||
var parameters = method.Parameters; |
||||
|
||||
if (index < 0 || index >= parameters.Count) |
||||
return null; |
||||
|
||||
return parameters [index]; |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,508 @@
@@ -0,0 +1,508 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Diagnostics; |
||||
using System.Linq; |
||||
using Decompiler; |
||||
using Mono.Cecil; |
||||
using Mono.Cecil.Cil; |
||||
|
||||
namespace Decompiler |
||||
{ |
||||
/// <summary>
|
||||
/// Assigns C# types to IL expressions.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Types are inferred in a bidirectional manner:
|
||||
/// The expected type flows from the outside to the inside, the actual inferred type flows from the inside to the outside.
|
||||
/// </remarks>
|
||||
public class TypeAnalysis |
||||
{ |
||||
public static void Run(DecompilerContext context, ILNode node) |
||||
{ |
||||
TypeAnalysis ta = new TypeAnalysis(); |
||||
ta.context = context; |
||||
ta.module = context.CurrentMethod.Module; |
||||
ta.typeSystem = ta.module.TypeSystem; |
||||
ta.InferTypes(node); |
||||
} |
||||
|
||||
DecompilerContext context; |
||||
TypeSystem typeSystem; |
||||
ModuleDefinition module; |
||||
List<ILExpression> storedToGeneratedVariables = new List<ILExpression>(); |
||||
|
||||
void InferTypes(ILNode node) |
||||
{ |
||||
foreach (ILNode child in node.GetChildren()) { |
||||
ILExpression expr = child as ILExpression; |
||||
if (expr != null) { |
||||
ILVariable v = expr.Operand as ILVariable; |
||||
if (v != null && v.IsGenerated && v.Type == null && expr.Code == ILCode.Stloc) { |
||||
// don't deal with this node or its children yet,
|
||||
// wait for the expected type to be inferred first
|
||||
storedToGeneratedVariables.Add(expr); |
||||
continue; |
||||
} |
||||
bool anyArgumentIsMissingType = expr.Arguments.Any(a => a.InferredType == null); |
||||
if (expr.InferredType == null || anyArgumentIsMissingType) |
||||
expr.InferredType = InferTypeForExpression(expr, null, forceInferChildren: anyArgumentIsMissingType); |
||||
} |
||||
InferTypes(child); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Infers the C# type of <paramref name="expr"/>.
|
||||
/// </summary>
|
||||
/// <param name="expr">The expression</param>
|
||||
/// <param name="expectedType">The expected type of the expression</param>
|
||||
/// <param name="forceInferChildren">Whether direct children should be inferred even if its not necessary. (does not apply to nested children!)</param>
|
||||
/// <returns>The inferred type</returns>
|
||||
TypeReference InferTypeForExpression(ILExpression expr, TypeReference expectedType, bool forceInferChildren = false) |
||||
{ |
||||
if (forceInferChildren || expr.InferredType == null) |
||||
expr.InferredType = DoInferTypeForExpression(expr, expectedType, forceInferChildren); |
||||
return expr.InferredType; |
||||
} |
||||
|
||||
TypeReference DoInferTypeForExpression(ILExpression expr, TypeReference expectedType, bool forceInferChildren = false) |
||||
{ |
||||
switch ((Code)expr.Code) { |
||||
#region Variable load/store
|
||||
case Code.Stloc: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments.Single(), ((ILVariable)expr.Operand).Type); |
||||
return null; |
||||
case Code.Ldloc: |
||||
return ((ILVariable)expr.Operand).Type; |
||||
case Code.Starg: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments.Single(), ((ParameterReference)expr.Operand).ParameterType); |
||||
return null; |
||||
case Code.Ldarg: |
||||
return ((ParameterReference)expr.Operand).ParameterType; |
||||
case Code.Ldloca: |
||||
return new ByReferenceType(((ILVariable)expr.Operand).Type); |
||||
case Code.Ldarga: |
||||
return new ByReferenceType(((ParameterReference)expr.Operand).ParameterType); |
||||
#endregion
|
||||
#region Call / NewObj
|
||||
case Code.Call: |
||||
case Code.Callvirt: |
||||
{ |
||||
MethodReference method = (MethodReference)expr.Operand; |
||||
if (forceInferChildren) { |
||||
for (int i = 0; i < expr.Arguments.Count; i++) { |
||||
if (i == 0 && method.HasThis) |
||||
InferTypeForExpression(expr.Arguments[i], method.DeclaringType); |
||||
else |
||||
InferTypeForExpression(expr.Arguments[i], method.Parameters[method.HasThis ? i - 1: i].ParameterType); |
||||
} |
||||
} |
||||
return method.ReturnType; |
||||
} |
||||
case Code.Newobj: |
||||
{ |
||||
MethodReference ctor = (MethodReference)expr.Operand; |
||||
if (forceInferChildren) { |
||||
for (int i = 0; i < ctor.Parameters.Count; i++) { |
||||
InferTypeForExpression(expr.Arguments[i], ctor.Parameters[i].ParameterType); |
||||
} |
||||
} |
||||
return ctor.DeclaringType; |
||||
} |
||||
#endregion
|
||||
#region Load/Store Fields
|
||||
case Code.Ldfld: |
||||
return UnpackModifiers(((FieldReference)expr.Operand).FieldType); |
||||
case Code.Ldsfld: |
||||
return UnpackModifiers(((FieldReference)expr.Operand).FieldType); |
||||
case Code.Ldflda: |
||||
case Code.Ldsflda: |
||||
return new ByReferenceType(UnpackModifiers(((FieldReference)expr.Operand).FieldType)); |
||||
case Code.Stfld: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments[1], ((FieldReference)expr.Operand).FieldType); |
||||
return null; |
||||
case Code.Stsfld: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments[0], ((FieldReference)expr.Operand).FieldType); |
||||
return null; |
||||
#endregion
|
||||
#region Reference/Pointer instructions
|
||||
case Code.Ldind_I: |
||||
case Code.Ldind_I1: |
||||
case Code.Ldind_I2: |
||||
case Code.Ldind_I4: |
||||
case Code.Ldind_I8: |
||||
case Code.Ldind_U1: |
||||
case Code.Ldind_U2: |
||||
case Code.Ldind_U4: |
||||
case Code.Ldind_R4: |
||||
case Code.Ldind_R8: |
||||
case Code.Ldind_Ref: |
||||
return UnpackPointer(InferTypeForExpression(expr.Arguments[0], null)); |
||||
case Code.Stind_I1: |
||||
case Code.Stind_I2: |
||||
case Code.Stind_I4: |
||||
case Code.Stind_I8: |
||||
case Code.Stind_R4: |
||||
case Code.Stind_R8: |
||||
case Code.Stind_I: |
||||
case Code.Stind_Ref: |
||||
if (forceInferChildren) { |
||||
TypeReference elementType = UnpackPointer(InferTypeForExpression(expr.Arguments[0], null)); |
||||
InferTypeForExpression(expr.Arguments[1], elementType); |
||||
} |
||||
return null; |
||||
case Code.Ldobj: |
||||
return (TypeReference)expr.Operand; |
||||
case Code.Stobj: |
||||
if (forceInferChildren) { |
||||
InferTypeForExpression(expr.Arguments[1], (TypeReference)expr.Operand); |
||||
} |
||||
return null; |
||||
case Code.Initobj: |
||||
return null; |
||||
case Code.Localloc: |
||||
return typeSystem.IntPtr; |
||||
#endregion
|
||||
#region Arithmetic instructions
|
||||
case Code.Not: // bitwise complement
|
||||
case Code.Neg: |
||||
return InferTypeForExpression(expr.Arguments.Single(), expectedType); |
||||
case Code.Add: |
||||
case Code.Sub: |
||||
case Code.Mul: |
||||
case Code.Or: |
||||
case Code.And: |
||||
case Code.Xor: |
||||
return InferArgumentsInBinaryOperator(expr, null); |
||||
case Code.Add_Ovf: |
||||
case Code.Sub_Ovf: |
||||
case Code.Mul_Ovf: |
||||
case Code.Div: |
||||
case Code.Rem: |
||||
return InferArgumentsInBinaryOperator(expr, true); |
||||
case Code.Add_Ovf_Un: |
||||
case Code.Sub_Ovf_Un: |
||||
case Code.Mul_Ovf_Un: |
||||
case Code.Div_Un: |
||||
case Code.Rem_Un: |
||||
return InferArgumentsInBinaryOperator(expr, false); |
||||
case Code.Shl: |
||||
case Code.Shr: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments[1], typeSystem.Int32); |
||||
return InferTypeForExpression(expr.Arguments[0], typeSystem.Int32); |
||||
case Code.Shr_Un: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments[1], typeSystem.Int32); |
||||
return InferTypeForExpression(expr.Arguments[0], typeSystem.UInt32); |
||||
#endregion
|
||||
#region Constant loading instructions
|
||||
case Code.Ldnull: |
||||
return typeSystem.Object; |
||||
case Code.Ldstr: |
||||
return typeSystem.String; |
||||
case Code.Ldftn: |
||||
case Code.Ldvirtftn: |
||||
return typeSystem.IntPtr; |
||||
case Code.Ldc_I4: |
||||
return (IsIntegerOrEnum(expectedType) || expectedType == typeSystem.Boolean) ? expectedType : typeSystem.Int32; |
||||
case Code.Ldc_I8: |
||||
return (IsIntegerOrEnum(expectedType)) ? expectedType : typeSystem.Int64; |
||||
case Code.Ldc_R4: |
||||
return typeSystem.Single; |
||||
case Code.Ldc_R8: |
||||
return typeSystem.Double; |
||||
case Code.Ldtoken: |
||||
if (expr.Operand is TypeReference) |
||||
return new TypeReference("System", "RuntimeTypeHandle", module, module, true); |
||||
else if (expr.Operand is FieldReference) |
||||
return new TypeReference("System", "RuntimeFieldHandle", module, module, true); |
||||
else |
||||
return new TypeReference("System", "RuntimeMethodHandle", module, module, true); |
||||
case Code.Arglist: |
||||
return new TypeReference("System", "RuntimeArgumentHandle", module, module, true); |
||||
#endregion
|
||||
#region Array instructions
|
||||
case Code.Newarr: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments.Single(), typeSystem.Int32); |
||||
return new ArrayType((TypeReference)expr.Operand); |
||||
case Code.Ldlen: |
||||
return typeSystem.Int32; |
||||
case Code.Ldelem_U1: |
||||
case Code.Ldelem_U2: |
||||
case Code.Ldelem_U4: |
||||
case Code.Ldelem_I1: |
||||
case Code.Ldelem_I2: |
||||
case Code.Ldelem_I4: |
||||
case Code.Ldelem_I8: |
||||
case Code.Ldelem_I: |
||||
case Code.Ldelem_Ref: |
||||
{ |
||||
ArrayType arrayType = InferTypeForExpression(expr.Arguments[0], null) as ArrayType; |
||||
if (forceInferChildren) { |
||||
InferTypeForExpression(expr.Arguments[0], new ArrayType(typeSystem.Byte)); |
||||
InferTypeForExpression(expr.Arguments[1], typeSystem.Int32); |
||||
} |
||||
return arrayType != null ? arrayType.ElementType : null; |
||||
} |
||||
case Code.Ldelem_Any: |
||||
if (forceInferChildren) { |
||||
InferTypeForExpression(expr.Arguments[1], typeSystem.Int32); |
||||
} |
||||
return (TypeReference)expr.Operand; |
||||
case Code.Ldelema: |
||||
{ |
||||
ArrayType arrayType = InferTypeForExpression(expr.Arguments[0], null) as ArrayType; |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments[1], typeSystem.Int32); |
||||
return arrayType != null ? new ByReferenceType(arrayType.ElementType) : null; |
||||
} |
||||
case Code.Stelem_I: |
||||
case Code.Stelem_I1: |
||||
case Code.Stelem_I2: |
||||
case Code.Stelem_I4: |
||||
case Code.Stelem_I8: |
||||
case Code.Stelem_R4: |
||||
case Code.Stelem_R8: |
||||
case Code.Stelem_Ref: |
||||
case Code.Stelem_Any: |
||||
if (forceInferChildren) { |
||||
ArrayType arrayType = InferTypeForExpression(expr.Arguments[0], null) as ArrayType; |
||||
InferTypeForExpression(expr.Arguments[1], typeSystem.Int32); |
||||
if (arrayType != null) { |
||||
InferTypeForExpression(expr.Arguments[2], arrayType.ElementType); |
||||
} |
||||
} |
||||
return null; |
||||
#endregion
|
||||
#region Conversion instructions
|
||||
case Code.Conv_I1: |
||||
case Code.Conv_Ovf_I1: |
||||
return (GetInformationAmount(expectedType) == 8 && IsSigned(expectedType) == true) ? expectedType : typeSystem.SByte; |
||||
case Code.Conv_I2: |
||||
case Code.Conv_Ovf_I2: |
||||
return (GetInformationAmount(expectedType) == 16 && IsSigned(expectedType) == true) ? expectedType : typeSystem.Int16; |
||||
case Code.Conv_I4: |
||||
case Code.Conv_Ovf_I4: |
||||
return (GetInformationAmount(expectedType) == 32 && IsSigned(expectedType) == true) ? expectedType : typeSystem.Int32; |
||||
case Code.Conv_I8: |
||||
case Code.Conv_Ovf_I8: |
||||
return (GetInformationAmount(expectedType) == 64 && IsSigned(expectedType) == true) ? expectedType : typeSystem.Int64; |
||||
case Code.Conv_U1: |
||||
case Code.Conv_Ovf_U1: |
||||
return (GetInformationAmount(expectedType) == 8 && IsSigned(expectedType) == false) ? expectedType : typeSystem.Byte; |
||||
case Code.Conv_U2: |
||||
case Code.Conv_Ovf_U2: |
||||
return (GetInformationAmount(expectedType) == 16 && IsSigned(expectedType) == false) ? expectedType : typeSystem.UInt16; |
||||
case Code.Conv_U4: |
||||
case Code.Conv_Ovf_U4: |
||||
return (GetInformationAmount(expectedType) == 32 && IsSigned(expectedType) == false) ? expectedType : typeSystem.UInt32; |
||||
case Code.Conv_U8: |
||||
case Code.Conv_Ovf_U8: |
||||
return (GetInformationAmount(expectedType) == 64 && IsSigned(expectedType) == false) ? expectedType : typeSystem.UInt64; |
||||
case Code.Conv_I: |
||||
case Code.Conv_Ovf_I: |
||||
return (GetInformationAmount(expectedType) == nativeInt && IsSigned(expectedType) == true) ? expectedType : typeSystem.IntPtr; |
||||
case Code.Conv_U: |
||||
case Code.Conv_Ovf_U: |
||||
return (GetInformationAmount(expectedType) == nativeInt && IsSigned(expectedType) == false) ? expectedType : typeSystem.UIntPtr; |
||||
case Code.Conv_R4: |
||||
return typeSystem.Single; |
||||
case Code.Conv_R8: |
||||
return typeSystem.Double; |
||||
case Code.Conv_R_Un: |
||||
return (expectedType == typeSystem.Single) ? typeSystem.Single : typeSystem.Double; |
||||
case Code.Castclass: |
||||
case Code.Isinst: |
||||
case Code.Unbox_Any: |
||||
return (TypeReference)expr.Operand; |
||||
case Code.Box: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments.Single(), (TypeReference)expr.Operand); |
||||
return (TypeReference)expr.Operand; |
||||
#endregion
|
||||
#region Comparison instructions
|
||||
case Code.Ceq: |
||||
if (forceInferChildren) |
||||
InferArgumentsInBinaryOperator(expr, null); |
||||
return typeSystem.Boolean; |
||||
case Code.Clt: |
||||
case Code.Cgt: |
||||
if (forceInferChildren) |
||||
InferArgumentsInBinaryOperator(expr, true); |
||||
return typeSystem.Boolean; |
||||
case Code.Clt_Un: |
||||
case Code.Cgt_Un: |
||||
if (forceInferChildren) |
||||
InferArgumentsInBinaryOperator(expr, false); |
||||
return typeSystem.Boolean; |
||||
#endregion
|
||||
#region Branch instructions
|
||||
case Code.Beq: |
||||
case Code.Bne_Un: |
||||
if (forceInferChildren) |
||||
InferArgumentsInBinaryOperator(expr, null); |
||||
return null; |
||||
case Code.Brtrue: |
||||
case Code.Brfalse: |
||||
if (forceInferChildren) |
||||
InferTypeForExpression(expr.Arguments.Single(), typeSystem.Boolean); |
||||
return null; |
||||
case Code.Blt: |
||||
case Code.Ble: |
||||
case Code.Bgt: |
||||
case Code.Bge: |
||||
if (forceInferChildren) |
||||
InferArgumentsInBinaryOperator(expr, true); |
||||
return null; |
||||
case Code.Blt_Un: |
||||
case Code.Ble_Un: |
||||
case Code.Bgt_Un: |
||||
case Code.Bge_Un: |
||||
if (forceInferChildren) |
||||
InferArgumentsInBinaryOperator(expr, false); |
||||
return null; |
||||
case Code.Br: |
||||
case Code.Leave: |
||||
case Code.Endfinally: |
||||
case Code.Switch: |
||||
case Code.Throw: |
||||
case Code.Rethrow: |
||||
return null; |
||||
case Code.Ret: |
||||
if (forceInferChildren && expr.Arguments.Count == 1) |
||||
InferTypeForExpression(expr.Arguments[0], context.CurrentMethod.ReturnType); |
||||
return null; |
||||
#endregion
|
||||
case Code.Pop: |
||||
return null; |
||||
case Code.Dup: |
||||
return InferTypeForExpression(expr.Arguments.Single(), expectedType); |
||||
default: |
||||
Debug.WriteLine("Type Inference: Can't handle " + expr.Code.GetName()); |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
TypeReference UnpackPointer(TypeReference pointerOrManagedReference) |
||||
{ |
||||
ByReferenceType refType = pointerOrManagedReference as ByReferenceType; |
||||
if (refType != null) |
||||
return refType.ElementType; |
||||
PointerType ptrType = pointerOrManagedReference as PointerType; |
||||
if (ptrType != null) |
||||
return ptrType.ElementType; |
||||
return null; |
||||
} |
||||
|
||||
static TypeReference UnpackModifiers(TypeReference type) |
||||
{ |
||||
while (type is OptionalModifierType || type is RequiredModifierType) |
||||
type = ((TypeSpecification)type).ElementType; |
||||
return type; |
||||
} |
||||
|
||||
TypeReference InferArgumentsInBinaryOperator(ILExpression expr, bool? isSigned) |
||||
{ |
||||
ILExpression left = expr.Arguments[0]; |
||||
ILExpression right = expr.Arguments[1]; |
||||
TypeReference leftPreferred = DoInferTypeForExpression(left, null); |
||||
TypeReference rightPreferred = DoInferTypeForExpression(right, null); |
||||
if (leftPreferred == rightPreferred) { |
||||
return left.InferredType = right.InferredType = leftPreferred; |
||||
} else if (rightPreferred == DoInferTypeForExpression(left, rightPreferred)) { |
||||
return left.InferredType = right.InferredType = rightPreferred; |
||||
} else if (leftPreferred == DoInferTypeForExpression(right, leftPreferred)) { |
||||
return left.InferredType = right.InferredType = leftPreferred; |
||||
} else { |
||||
return left.InferredType = right.InferredType = TypeWithMoreInformation(leftPreferred, rightPreferred); |
||||
} |
||||
} |
||||
|
||||
TypeReference TypeWithMoreInformation(TypeReference leftPreferred, TypeReference rightPreferred) |
||||
{ |
||||
int left = GetInformationAmount(typeSystem, leftPreferred); |
||||
int right = GetInformationAmount(typeSystem, rightPreferred); |
||||
if (left < right) |
||||
return rightPreferred; |
||||
else |
||||
return leftPreferred; |
||||
} |
||||
|
||||
int GetInformationAmount(TypeReference type) |
||||
{ |
||||
return GetInformationAmount(typeSystem, type); |
||||
} |
||||
|
||||
const int nativeInt = 33; // treat native int as between int32 and int64
|
||||
|
||||
static int GetInformationAmount(TypeSystem typeSystem, TypeReference type) |
||||
{ |
||||
if (type == null) |
||||
return 0; |
||||
if (type.IsValueType) { |
||||
// value type might be an enum
|
||||
TypeDefinition typeDef = type.Resolve() as TypeDefinition; |
||||
if (typeDef != null && typeDef.IsEnum) { |
||||
TypeReference underlyingType = typeDef.Fields.Single(f => f.IsRuntimeSpecialName && !f.IsStatic).FieldType; |
||||
return GetInformationAmount(typeDef.Module.TypeSystem, underlyingType); |
||||
} |
||||
} |
||||
if (type == typeSystem.Boolean) |
||||
return 1; |
||||
else if (type == typeSystem.Byte || type == typeSystem.SByte) |
||||
return 8; |
||||
else if (type == typeSystem.Int16 || type == typeSystem.UInt16) |
||||
return 16; |
||||
else if (type == typeSystem.Int32 || type == typeSystem.UInt32) |
||||
return 32; |
||||
else if (type == typeSystem.IntPtr || type == typeSystem.UIntPtr) |
||||
return nativeInt; |
||||
else if (type == typeSystem.Int64 || type == typeSystem.UInt64) |
||||
return 64; |
||||
return 100; // we consider structs/objects to have more information than any primitives
|
||||
} |
||||
|
||||
bool IsIntegerOrEnum(TypeReference type) |
||||
{ |
||||
return IsIntegerOrEnum(typeSystem, type); |
||||
} |
||||
|
||||
public static bool IsIntegerOrEnum(TypeSystem typeSystem, TypeReference type) |
||||
{ |
||||
return IsSigned(typeSystem, type) != null; |
||||
} |
||||
|
||||
bool? IsSigned(TypeReference type) |
||||
{ |
||||
return IsSigned(typeSystem, type); |
||||
} |
||||
|
||||
static bool? IsSigned(TypeSystem typeSystem, TypeReference type) |
||||
{ |
||||
if (type == null) |
||||
return null; |
||||
if (type.IsValueType) { |
||||
// value type might be an enum
|
||||
TypeDefinition typeDef = type.Resolve() as TypeDefinition; |
||||
if (typeDef != null && typeDef.IsEnum) { |
||||
TypeReference underlyingType = typeDef.Fields.Single(f => f.IsRuntimeSpecialName && !f.IsStatic).FieldType; |
||||
return IsSigned(typeDef.Module.TypeSystem, underlyingType); |
||||
} |
||||
} |
||||
if (type == typeSystem.Byte || type == typeSystem.UInt16 || type == typeSystem.UInt32 || type == typeSystem.UInt64 || type == typeSystem.UIntPtr) |
||||
return false; |
||||
if (type == typeSystem.SByte || type == typeSystem.Int16 || type == typeSystem.Int32 || type == typeSystem.Int64 || type == typeSystem.IntPtr) |
||||
return true; |
||||
return null; |
||||
} |
||||
} |
||||
} |
||||
@ -1,15 +0,0 @@
@@ -1,15 +0,0 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
|
||||
namespace Decompiler |
||||
{ |
||||
public class Constants |
||||
{ |
||||
public const string Object = "System.Object"; |
||||
public const string Int32 = "System.Int32"; |
||||
public const string Boolean = "System.Boolean"; |
||||
public const string Void = "System.Void"; |
||||
} |
||||
} |
||||
@ -1,478 +0,0 @@
@@ -1,478 +0,0 @@
|
||||
//
|
||||
// MethodBodyRocks.cs
|
||||
//
|
||||
// Author:
|
||||
// Jb Evain (jbevain@gmail.com)
|
||||
//
|
||||
// Copyright (c) 2008 - 2010 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 System; |
||||
|
||||
using Mono.Cecil.Cil; |
||||
|
||||
namespace Mono.Cecil.Rocks { |
||||
|
||||
#if INSIDE_ROCKS
|
||||
public |
||||
#endif
|
||||
static class MethodBodyRocks { |
||||
|
||||
public static ParameterDefinition GetParameter (this MethodBody self, int index) |
||||
{ |
||||
var method = self.Method; |
||||
|
||||
if (method.HasThis) { |
||||
if (index == 0) |
||||
return self.ThisParameter; |
||||
|
||||
index--; |
||||
} |
||||
|
||||
var parameters = method.Parameters; |
||||
|
||||
if (index < 0 || index >= parameters.Count) |
||||
return null; |
||||
|
||||
return parameters [index]; |
||||
} |
||||
|
||||
public static void SimplifyMacros (this MethodBody self) |
||||
{ |
||||
if (self == null) |
||||
throw new ArgumentNullException ("self"); |
||||
|
||||
foreach (var instruction in self.Instructions) { |
||||
if (instruction.OpCode.OpCodeType != OpCodeType.Macro) |
||||
continue; |
||||
|
||||
switch (instruction.OpCode.Code) { |
||||
case Code.Ldarg_0: |
||||
ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (0)); |
||||
break; |
||||
case Code.Ldarg_1: |
||||
ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (1)); |
||||
break; |
||||
case Code.Ldarg_2: |
||||
ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (2)); |
||||
break; |
||||
case Code.Ldarg_3: |
||||
ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (3)); |
||||
break; |
||||
case Code.Ldloc_0: |
||||
ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [0]); |
||||
break; |
||||
case Code.Ldloc_1: |
||||
ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [1]); |
||||
break; |
||||
case Code.Ldloc_2: |
||||
ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [2]); |
||||
break; |
||||
case Code.Ldloc_3: |
||||
ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [3]); |
||||
break; |
||||
case Code.Stloc_0: |
||||
ExpandMacro (instruction, OpCodes.Stloc, self.Variables [0]); |
||||
break; |
||||
case Code.Stloc_1: |
||||
ExpandMacro (instruction, OpCodes.Stloc, self.Variables [1]); |
||||
break; |
||||
case Code.Stloc_2: |
||||
ExpandMacro (instruction, OpCodes.Stloc, self.Variables [2]); |
||||
break; |
||||
case Code.Stloc_3: |
||||
ExpandMacro (instruction, OpCodes.Stloc, self.Variables [3]); |
||||
break; |
||||
case Code.Ldarg_S: |
||||
instruction.OpCode = OpCodes.Ldarg; |
||||
break; |
||||
case Code.Ldarga_S: |
||||
instruction.OpCode = OpCodes.Ldarga; |
||||
break; |
||||
case Code.Starg_S: |
||||
instruction.OpCode = OpCodes.Starg; |
||||
break; |
||||
case Code.Ldloc_S: |
||||
instruction.OpCode = OpCodes.Ldloc; |
||||
break; |
||||
case Code.Ldloca_S: |
||||
instruction.OpCode = OpCodes.Ldloca; |
||||
break; |
||||
case Code.Stloc_S: |
||||
instruction.OpCode = OpCodes.Stloc; |
||||
break; |
||||
case Code.Ldc_I4_M1: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, -1); |
||||
break; |
||||
case Code.Ldc_I4_0: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 0); |
||||
break; |
||||
case Code.Ldc_I4_1: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 1); |
||||
break; |
||||
case Code.Ldc_I4_2: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 2); |
||||
break; |
||||
case Code.Ldc_I4_3: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 3); |
||||
break; |
||||
case Code.Ldc_I4_4: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 4); |
||||
break; |
||||
case Code.Ldc_I4_5: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 5); |
||||
break; |
||||
case Code.Ldc_I4_6: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 6); |
||||
break; |
||||
case Code.Ldc_I4_7: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 7); |
||||
break; |
||||
case Code.Ldc_I4_8: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, 8); |
||||
break; |
||||
case Code.Ldc_I4_S: |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4, (int) (sbyte) instruction.Operand); |
||||
break; |
||||
case Code.Br_S: |
||||
instruction.OpCode = OpCodes.Br; |
||||
break; |
||||
case Code.Brfalse_S: |
||||
instruction.OpCode = OpCodes.Brfalse; |
||||
break; |
||||
case Code.Brtrue_S: |
||||
instruction.OpCode = OpCodes.Brtrue; |
||||
break; |
||||
case Code.Beq_S: |
||||
instruction.OpCode = OpCodes.Beq; |
||||
break; |
||||
case Code.Bge_S: |
||||
instruction.OpCode = OpCodes.Bge; |
||||
break; |
||||
case Code.Bgt_S: |
||||
instruction.OpCode = OpCodes.Bgt; |
||||
break; |
||||
case Code.Ble_S: |
||||
instruction.OpCode = OpCodes.Ble; |
||||
break; |
||||
case Code.Blt_S: |
||||
instruction.OpCode = OpCodes.Blt; |
||||
break; |
||||
case Code.Bne_Un_S: |
||||
instruction.OpCode = OpCodes.Bne_Un; |
||||
break; |
||||
case Code.Bge_Un_S: |
||||
instruction.OpCode = OpCodes.Bge_Un; |
||||
break; |
||||
case Code.Bgt_Un_S: |
||||
instruction.OpCode = OpCodes.Bgt_Un; |
||||
break; |
||||
case Code.Ble_Un_S: |
||||
instruction.OpCode = OpCodes.Ble_Un; |
||||
break; |
||||
case Code.Blt_Un_S: |
||||
instruction.OpCode = OpCodes.Blt_Un; |
||||
break; |
||||
case Code.Leave_S: |
||||
instruction.OpCode = OpCodes.Leave; |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void ExpandMacro(ref OpCode opCode, ref object operand, MethodBody methodBody) |
||||
{ |
||||
if (opCode.OpCodeType != OpCodeType.Macro) |
||||
return; |
||||
|
||||
switch (opCode.Code) { |
||||
case Code.Ldarg_0: opCode = OpCodes.Ldarg; operand = methodBody.GetParameter(0); break; |
||||
case Code.Ldarg_1: opCode = OpCodes.Ldarg; operand = methodBody.GetParameter(1); break; |
||||
case Code.Ldarg_2: opCode = OpCodes.Ldarg; operand = methodBody.GetParameter(2); break; |
||||
case Code.Ldarg_3: opCode = OpCodes.Ldarg; operand = methodBody.GetParameter(3); break; |
||||
case Code.Ldloc_0: opCode = OpCodes.Ldloc; operand = methodBody.Variables[0]; break; |
||||
case Code.Ldloc_1: opCode = OpCodes.Ldloc; operand = methodBody.Variables[1]; break; |
||||
case Code.Ldloc_2: opCode = OpCodes.Ldloc; operand = methodBody.Variables[2]; break; |
||||
case Code.Ldloc_3: opCode = OpCodes.Ldloc; operand = methodBody.Variables[3]; break; |
||||
case Code.Stloc_0: opCode = OpCodes.Stloc; operand = methodBody.Variables[0]; break; |
||||
case Code.Stloc_1: opCode = OpCodes.Stloc; operand = methodBody.Variables[1]; break; |
||||
case Code.Stloc_2: opCode = OpCodes.Stloc; operand = methodBody.Variables[2]; break; |
||||
case Code.Stloc_3: opCode = OpCodes.Stloc; operand = methodBody.Variables[3]; break; |
||||
case Code.Ldarg_S: opCode = OpCodes.Ldarg; break; |
||||
case Code.Ldarga_S: opCode = OpCodes.Ldarga; break; |
||||
case Code.Starg_S: opCode = OpCodes.Starg; break; |
||||
case Code.Ldloc_S: opCode = OpCodes.Ldloc; break; |
||||
case Code.Ldloca_S: opCode = OpCodes.Ldloca; break; |
||||
case Code.Stloc_S: opCode = OpCodes.Stloc; break; |
||||
case Code.Ldc_I4_M1: opCode = OpCodes.Ldc_I4; operand = -1; break; |
||||
case Code.Ldc_I4_0: opCode = OpCodes.Ldc_I4; operand = 0; break; |
||||
case Code.Ldc_I4_1: opCode = OpCodes.Ldc_I4; operand = 1; break; |
||||
case Code.Ldc_I4_2: opCode = OpCodes.Ldc_I4; operand = 2; break; |
||||
case Code.Ldc_I4_3: opCode = OpCodes.Ldc_I4; operand = 3; break; |
||||
case Code.Ldc_I4_4: opCode = OpCodes.Ldc_I4; operand = 4; break; |
||||
case Code.Ldc_I4_5: opCode = OpCodes.Ldc_I4; operand = 5; break; |
||||
case Code.Ldc_I4_6: opCode = OpCodes.Ldc_I4; operand = 6; break; |
||||
case Code.Ldc_I4_7: opCode = OpCodes.Ldc_I4; operand = 7; break; |
||||
case Code.Ldc_I4_8: opCode = OpCodes.Ldc_I4; operand = 8; break; |
||||
case Code.Ldc_I4_S: opCode = OpCodes.Ldc_I4; operand = (int) (sbyte) operand; break; |
||||
case Code.Br_S: opCode = OpCodes.Br; break; |
||||
case Code.Brfalse_S: opCode = OpCodes.Brfalse; break; |
||||
case Code.Brtrue_S: opCode = OpCodes.Brtrue; break; |
||||
case Code.Beq_S: opCode = OpCodes.Beq; break; |
||||
case Code.Bge_S: opCode = OpCodes.Bge; break; |
||||
case Code.Bgt_S: opCode = OpCodes.Bgt; break; |
||||
case Code.Ble_S: opCode = OpCodes.Ble; break; |
||||
case Code.Blt_S: opCode = OpCodes.Blt; break; |
||||
case Code.Bne_Un_S: opCode = OpCodes.Bne_Un; break; |
||||
case Code.Bge_Un_S: opCode = OpCodes.Bge_Un; break; |
||||
case Code.Bgt_Un_S: opCode = OpCodes.Bgt_Un; break; |
||||
case Code.Ble_Un_S: opCode = OpCodes.Ble_Un; break; |
||||
case Code.Blt_Un_S: opCode = OpCodes.Blt_Un; break; |
||||
case Code.Leave_S: opCode = OpCodes.Leave; break; |
||||
} |
||||
} |
||||
|
||||
static void ExpandMacro (Instruction instruction, OpCode opcode, object operand) |
||||
{ |
||||
instruction.OpCode = opcode; |
||||
instruction.Operand = operand; |
||||
} |
||||
|
||||
static void MakeMacro (Instruction instruction, OpCode opcode) |
||||
{ |
||||
instruction.OpCode = opcode; |
||||
instruction.Operand = null; |
||||
} |
||||
|
||||
public static void OptimizeMacros (this MethodBody self) |
||||
{ |
||||
if (self == null) |
||||
throw new ArgumentNullException ("self"); |
||||
|
||||
var method = self.Method; |
||||
|
||||
foreach (var instruction in self.Instructions) { |
||||
int index; |
||||
switch (instruction.OpCode.Code) { |
||||
case Code.Ldarg: |
||||
index = ((ParameterDefinition) instruction.Operand).Index; |
||||
if (index == -1 && instruction.Operand == self.ThisParameter) |
||||
index = 0; |
||||
else if (method.HasThis) |
||||
index++; |
||||
|
||||
switch (index) { |
||||
case 0: |
||||
MakeMacro (instruction, OpCodes.Ldarg_0); |
||||
break; |
||||
case 1: |
||||
MakeMacro (instruction, OpCodes.Ldarg_1); |
||||
break; |
||||
case 2: |
||||
MakeMacro (instruction, OpCodes.Ldarg_2); |
||||
break; |
||||
case 3: |
||||
MakeMacro (instruction, OpCodes.Ldarg_3); |
||||
break; |
||||
default: |
||||
if (index < 256) |
||||
ExpandMacro (instruction, OpCodes.Ldarg_S, instruction.Operand); |
||||
break; |
||||
} |
||||
break; |
||||
case Code.Ldloc: |
||||
index = ((VariableDefinition) instruction.Operand).Index; |
||||
switch (index) { |
||||
case 0: |
||||
MakeMacro (instruction, OpCodes.Ldloc_0); |
||||
break; |
||||
case 1: |
||||
MakeMacro (instruction, OpCodes.Ldloc_1); |
||||
break; |
||||
case 2: |
||||
MakeMacro (instruction, OpCodes.Ldloc_2); |
||||
break; |
||||
case 3: |
||||
MakeMacro (instruction, OpCodes.Ldloc_3); |
||||
break; |
||||
default: |
||||
if (index < 256) |
||||
ExpandMacro (instruction, OpCodes.Ldloc_S, instruction.Operand); |
||||
break; |
||||
} |
||||
break; |
||||
case Code.Stloc: |
||||
index = ((VariableDefinition) instruction.Operand).Index; |
||||
switch (index) { |
||||
case 0: |
||||
MakeMacro (instruction, OpCodes.Stloc_0); |
||||
break; |
||||
case 1: |
||||
MakeMacro (instruction, OpCodes.Stloc_1); |
||||
break; |
||||
case 2: |
||||
MakeMacro (instruction, OpCodes.Stloc_2); |
||||
break; |
||||
case 3: |
||||
MakeMacro (instruction, OpCodes.Stloc_3); |
||||
break; |
||||
default: |
||||
if (index < 256) |
||||
ExpandMacro (instruction, OpCodes.Stloc_S, instruction.Operand); |
||||
break; |
||||
} |
||||
break; |
||||
case Code.Ldarga: |
||||
index = ((ParameterDefinition) instruction.Operand).Index; |
||||
if (index == -1 && instruction.Operand == self.ThisParameter) |
||||
index = 0; |
||||
else if (method.HasThis) |
||||
index++; |
||||
if (index < 256) |
||||
ExpandMacro (instruction, OpCodes.Ldarga_S, instruction.Operand); |
||||
break; |
||||
case Code.Ldloca: |
||||
if (((VariableDefinition) instruction.Operand).Index < 256) |
||||
ExpandMacro (instruction, OpCodes.Ldloca_S, instruction.Operand); |
||||
break; |
||||
case Code.Ldc_I4: |
||||
int i = (int) instruction.Operand; |
||||
switch (i) { |
||||
case -1: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_M1); |
||||
break; |
||||
case 0: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_0); |
||||
break; |
||||
case 1: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_1); |
||||
break; |
||||
case 2: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_2); |
||||
break; |
||||
case 3: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_3); |
||||
break; |
||||
case 4: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_4); |
||||
break; |
||||
case 5: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_5); |
||||
break; |
||||
case 6: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_6); |
||||
break; |
||||
case 7: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_7); |
||||
break; |
||||
case 8: |
||||
MakeMacro (instruction, OpCodes.Ldc_I4_8); |
||||
break; |
||||
default: |
||||
if (i >= -128 && i < 128) |
||||
ExpandMacro (instruction, OpCodes.Ldc_I4_S, (sbyte) i); |
||||
break; |
||||
} |
||||
break; |
||||
} |
||||
} |
||||
|
||||
OptimizeBranches (self); |
||||
} |
||||
|
||||
static void OptimizeBranches (MethodBody body) |
||||
{ |
||||
ComputeOffsets (body); |
||||
|
||||
foreach (var instruction in body.Instructions) { |
||||
if (instruction.OpCode.OperandType != OperandType.InlineBrTarget) |
||||
continue; |
||||
|
||||
if (OptimizeBranch (instruction)) |
||||
ComputeOffsets (body); |
||||
} |
||||
} |
||||
|
||||
static bool OptimizeBranch (Instruction instruction) |
||||
{ |
||||
var offset = ((Instruction) instruction.Operand).Offset - (instruction.Offset + instruction.OpCode.Size + 4); |
||||
if (!(offset >= -128 && offset <= 127)) |
||||
return false; |
||||
|
||||
switch (instruction.OpCode.Code) { |
||||
case Code.Br: |
||||
instruction.OpCode = OpCodes.Br_S; |
||||
break; |
||||
case Code.Brfalse: |
||||
instruction.OpCode = OpCodes.Brfalse_S; |
||||
break; |
||||
case Code.Brtrue: |
||||
instruction.OpCode = OpCodes.Brtrue_S; |
||||
break; |
||||
case Code.Beq: |
||||
instruction.OpCode = OpCodes.Beq_S; |
||||
break; |
||||
case Code.Bge: |
||||
instruction.OpCode = OpCodes.Bge_S; |
||||
break; |
||||
case Code.Bgt: |
||||
instruction.OpCode = OpCodes.Bgt_S; |
||||
break; |
||||
case Code.Ble: |
||||
instruction.OpCode = OpCodes.Ble_S; |
||||
break; |
||||
case Code.Blt: |
||||
instruction.OpCode = OpCodes.Blt_S; |
||||
break; |
||||
case Code.Bne_Un: |
||||
instruction.OpCode = OpCodes.Bne_Un_S; |
||||
break; |
||||
case Code.Bge_Un: |
||||
instruction.OpCode = OpCodes.Bge_Un_S; |
||||
break; |
||||
case Code.Bgt_Un: |
||||
instruction.OpCode = OpCodes.Bgt_Un_S; |
||||
break; |
||||
case Code.Ble_Un: |
||||
instruction.OpCode = OpCodes.Ble_Un_S; |
||||
break; |
||||
case Code.Blt_Un: |
||||
instruction.OpCode = OpCodes.Blt_Un_S; |
||||
break; |
||||
case Code.Leave: |
||||
instruction.OpCode = OpCodes.Leave_S; |
||||
break; |
||||
} |
||||
|
||||
return true; |
||||
} |
||||
|
||||
static void ComputeOffsets (MethodBody body) |
||||
{ |
||||
var offset = 0; |
||||
foreach (var instruction in body.Instructions) { |
||||
instruction.Offset = offset; |
||||
offset += instruction.GetSize (); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
@ -1,359 +0,0 @@
@@ -1,359 +0,0 @@
|
||||
/* |
||||
* Created by SharpDevelop. |
||||
* User: User |
||||
* Date: 05/02/2011 |
||||
* Time: 10:10 |
||||
* |
||||
* To change this template use Tools | Options | Coding | Edit Standard Headers. |
||||
*/ |
||||
using System; |
||||
using System.Collections.Generic; |
||||
using Mono.Cecil; |
||||
using Mono.Cecil.Cil; |
||||
|
||||
namespace Decompiler.Rocks |
||||
{ |
||||
static class MyRocks |
||||
{ |
||||
static public TypeReference TypeVoid = GetCecilType(typeof(void)); |
||||
static public TypeReference TypeObject = GetCecilType(typeof(Object)); |
||||
static public TypeReference TypeException = GetCecilType(typeof(Exception)); |
||||
static public TypeReference TypeBool = GetCecilType(typeof(bool)); |
||||
static public TypeReference TypeInt32 = GetCecilType(typeof(Int32)); |
||||
static public TypeReference TypeString = GetCecilType(typeof(string)); |
||||
static public TypeReference TypeZero = GetCecilType(typeof(Int32)); |
||||
static public TypeReference TypeOne = GetCecilType(typeof(Int32)); |
||||
|
||||
public static List<T> CutRange<T>(this List<T> list, int start, int count) |
||||
{ |
||||
List<T> ret = new List<T>(count); |
||||
for (int i = 0; i < count; i++) { |
||||
ret.Add(list[start + i]); |
||||
} |
||||
list.RemoveRange(start, count); |
||||
return ret; |
||||
} |
||||
|
||||
public static bool CanFallThough(this OpCode opCode) |
||||
{ |
||||
switch(opCode.FlowControl) { |
||||
case FlowControl.Branch: return false; |
||||
case FlowControl.Cond_Branch: return true; |
||||
case FlowControl.Next: return true; |
||||
case FlowControl.Call: return true; |
||||
case FlowControl.Return: return false; |
||||
case FlowControl.Throw: return false; |
||||
case FlowControl.Meta: return true; |
||||
default: throw new NotImplementedException(); |
||||
} |
||||
} |
||||
|
||||
public static bool IsBranch(this OpCode opCode) |
||||
{ |
||||
return opCode.FlowControl == FlowControl.Branch || opCode.FlowControl == FlowControl.Cond_Branch; |
||||
} |
||||
|
||||
public static int? GetPopCount(this Instruction inst) |
||||
{ |
||||
switch(inst.OpCode.StackBehaviourPop) { |
||||
case StackBehaviour.Pop0: return 0; |
||||
case StackBehaviour.Pop1: return 1; |
||||
case StackBehaviour.Popi: return 1; |
||||
case StackBehaviour.Popref: return 1; |
||||
case StackBehaviour.Pop1_pop1: return 2; |
||||
case StackBehaviour.Popi_pop1: return 2; |
||||
case StackBehaviour.Popi_popi: return 2; |
||||
case StackBehaviour.Popi_popi8: return 2; |
||||
case StackBehaviour.Popi_popr4: return 2; |
||||
case StackBehaviour.Popi_popr8: return 2; |
||||
case StackBehaviour.Popref_pop1: return 2; |
||||
case StackBehaviour.Popref_popi: return 2; |
||||
case StackBehaviour.Popi_popi_popi: return 3; |
||||
case StackBehaviour.Popref_popi_popi: return 3; |
||||
case StackBehaviour.Popref_popi_popi8: return 3; |
||||
case StackBehaviour.Popref_popi_popr4: return 3; |
||||
case StackBehaviour.Popref_popi_popr8: return 3; |
||||
case StackBehaviour.Popref_popi_popref: return 3; |
||||
case StackBehaviour.PopAll: return null; |
||||
case StackBehaviour.Varpop: |
||||
switch(inst.OpCode.Code) { |
||||
case Code.Call: |
||||
case Code.Callvirt: |
||||
MethodReference cecilMethod = ((MethodReference)inst.Operand); |
||||
if (cecilMethod.HasThis) { |
||||
return cecilMethod.Parameters.Count + 1 /* this */; |
||||
} else { |
||||
return cecilMethod.Parameters.Count; |
||||
} |
||||
case Code.Calli: throw new NotImplementedException(); |
||||
case Code.Ret: return null; |
||||
case Code.Newobj: |
||||
MethodReference ctorMethod = ((MethodReference)inst.Operand); |
||||
return ctorMethod.Parameters.Count; |
||||
default: throw new Exception("Unknown Varpop opcode"); |
||||
} |
||||
default: throw new Exception("Unknown pop behaviour: " + inst.OpCode.StackBehaviourPop); |
||||
} |
||||
} |
||||
|
||||
public static int GetPushCount(this Instruction inst) |
||||
{ |
||||
switch(inst.OpCode.StackBehaviourPush) { |
||||
case StackBehaviour.Push0: return 0; |
||||
case StackBehaviour.Push1: return 1; |
||||
case StackBehaviour.Push1_push1: return 2; |
||||
case StackBehaviour.Pushi: return 1; |
||||
case StackBehaviour.Pushi8: return 1; |
||||
case StackBehaviour.Pushr4: return 1; |
||||
case StackBehaviour.Pushr8: return 1; |
||||
case StackBehaviour.Pushref: return 1; |
||||
case StackBehaviour.Varpush: // Happens only for calls
|
||||
switch(inst.OpCode.Code) { |
||||
case Code.Call: |
||||
case Code.Callvirt: |
||||
MethodReference cecilMethod = ((MethodReference)inst.Operand); |
||||
if (cecilMethod.ReturnType.FullName == Constants.Void) { |
||||
return 0; |
||||
} else { |
||||
return 1; |
||||
} |
||||
case Code.Calli: throw new NotImplementedException(); |
||||
default: throw new Exception("Unknown Varpush opcode"); |
||||
} |
||||
default: throw new Exception("Unknown push behaviour: " + inst.OpCode.StackBehaviourPush); |
||||
} |
||||
} |
||||
|
||||
static public TypeReference GetCecilType(Type type) |
||||
{ |
||||
return new TypeReference(type.Name, type.Namespace, null, null, type.IsValueType); |
||||
} |
||||
|
||||
static public TypeReference GetTypeInternal(this Instruction inst, MethodDefinition methodDef, List<TypeReference> args) |
||||
{ |
||||
OpCode opCode = inst.OpCode; |
||||
object operand = inst.Operand; |
||||
TypeReference operandAsTypeRef = operand as TypeReference; |
||||
//ByteCode operandAsByteCode = operand as ByteCode;
|
||||
//string operandAsByteCodeLabel = operand is ByteCode ? String.Format("IL_{0:X2}", ((ByteCode)operand).Offset) : null;
|
||||
TypeReference arg1 = args.Count >= 1 ? args[0] : null; |
||||
TypeReference arg2 = args.Count >= 2 ? args[1] : null; |
||||
TypeReference arg3 = args.Count >= 3 ? args[2] : null; |
||||
|
||||
switch(opCode.Code) { |
||||
#region Arithmetic
|
||||
case Code.Add: |
||||
case Code.Add_Ovf: |
||||
case Code.Add_Ovf_Un: |
||||
case Code.Div: |
||||
case Code.Div_Un: |
||||
case Code.Mul: |
||||
case Code.Mul_Ovf: |
||||
case Code.Mul_Ovf_Un: |
||||
case Code.Rem: |
||||
case Code.Rem_Un: |
||||
case Code.Sub: |
||||
case Code.Sub_Ovf: |
||||
case Code.Sub_Ovf_Un: |
||||
case Code.And: |
||||
case Code.Xor: |
||||
case Code.Shl: |
||||
case Code.Shr: |
||||
case Code.Shr_Un: return TypeInt32; |
||||
|
||||
case Code.Neg: return TypeInt32; |
||||
case Code.Not: return TypeInt32; |
||||
#endregion
|
||||
#region Arrays
|
||||
case Code.Newarr: |
||||
return new ArrayType(operandAsTypeRef); |
||||
|
||||
case Code.Ldlen: return TypeInt32; |
||||
|
||||
case Code.Ldelem_I: |
||||
case Code.Ldelem_I1: |
||||
case Code.Ldelem_I2: |
||||
case Code.Ldelem_I4: |
||||
case Code.Ldelem_I8: return TypeInt32; |
||||
case Code.Ldelem_U1: |
||||
case Code.Ldelem_U2: |
||||
case Code.Ldelem_U4: |
||||
case Code.Ldelem_R4: |
||||
case Code.Ldelem_R8: throw new NotImplementedException(); |
||||
case Code.Ldelem_Ref: |
||||
if (arg1 is ArrayType) { |
||||
return ((ArrayType)arg1).ElementType; |
||||
} else { |
||||
throw new NotImplementedException(); |
||||
} |
||||
case Code.Ldelem_Any: |
||||
case Code.Ldelema: throw new NotImplementedException(); |
||||
|
||||
case Code.Stelem_I: |
||||
case Code.Stelem_I1: |
||||
case Code.Stelem_I2: |
||||
case Code.Stelem_I4: |
||||
case Code.Stelem_I8: |
||||
case Code.Stelem_R4: |
||||
case Code.Stelem_R8: |
||||
case Code.Stelem_Ref: |
||||
case Code.Stelem_Any: return TypeVoid; |
||||
#endregion
|
||||
#region Branching
|
||||
case Code.Br: |
||||
case Code.Brfalse: |
||||
case Code.Brtrue: |
||||
case Code.Beq: |
||||
case Code.Bge: |
||||
case Code.Bge_Un: |
||||
case Code.Bgt: |
||||
case Code.Bgt_Un: |
||||
case Code.Ble: |
||||
case Code.Ble_Un: |
||||
case Code.Blt: |
||||
case Code.Blt_Un: |
||||
case Code.Bne_Un: return TypeVoid; |
||||
#endregion
|
||||
#region Comparison
|
||||
case Code.Ceq: |
||||
case Code.Cgt: |
||||
case Code.Cgt_Un: |
||||
case Code.Clt: |
||||
case Code.Clt_Un: return TypeBool; |
||||
#endregion
|
||||
#region Conversions
|
||||
case Code.Conv_I: |
||||
case Code.Conv_I1: |
||||
case Code.Conv_I2: |
||||
case Code.Conv_I4: |
||||
case Code.Conv_I8: |
||||
case Code.Conv_U: |
||||
case Code.Conv_U1: |
||||
case Code.Conv_U2: |
||||
case Code.Conv_U4: |
||||
case Code.Conv_U8: |
||||
case Code.Conv_R4: |
||||
case Code.Conv_R8: |
||||
case Code.Conv_R_Un: |
||||
|
||||
case Code.Conv_Ovf_I: |
||||
case Code.Conv_Ovf_I1: |
||||
case Code.Conv_Ovf_I2: |
||||
case Code.Conv_Ovf_I4: |
||||
case Code.Conv_Ovf_I8: |
||||
case Code.Conv_Ovf_U: |
||||
case Code.Conv_Ovf_U1: |
||||
case Code.Conv_Ovf_U2: |
||||
case Code.Conv_Ovf_U4: |
||||
case Code.Conv_Ovf_U8: |
||||
|
||||
case Code.Conv_Ovf_I_Un: |
||||
case Code.Conv_Ovf_I1_Un: |
||||
case Code.Conv_Ovf_I2_Un: |
||||
case Code.Conv_Ovf_I4_Un: |
||||
case Code.Conv_Ovf_I8_Un: |
||||
case Code.Conv_Ovf_U_Un: |
||||
case Code.Conv_Ovf_U1_Un: |
||||
case Code.Conv_Ovf_U2_Un: |
||||
case Code.Conv_Ovf_U4_Un: |
||||
case Code.Conv_Ovf_U8_Un: return TypeInt32; |
||||
#endregion
|
||||
#region Indirect
|
||||
case Code.Ldind_I: throw new NotImplementedException(); |
||||
case Code.Ldind_I1: throw new NotImplementedException(); |
||||
case Code.Ldind_I2: throw new NotImplementedException(); |
||||
case Code.Ldind_I4: throw new NotImplementedException(); |
||||
case Code.Ldind_I8: throw new NotImplementedException(); |
||||
case Code.Ldind_U1: throw new NotImplementedException(); |
||||
case Code.Ldind_U2: throw new NotImplementedException(); |
||||
case Code.Ldind_U4: throw new NotImplementedException(); |
||||
case Code.Ldind_R4: throw new NotImplementedException(); |
||||
case Code.Ldind_R8: throw new NotImplementedException(); |
||||
case Code.Ldind_Ref: throw new NotImplementedException(); |
||||
|
||||
case Code.Stind_I: throw new NotImplementedException(); |
||||
case Code.Stind_I1: throw new NotImplementedException(); |
||||
case Code.Stind_I2: throw new NotImplementedException(); |
||||
case Code.Stind_I4: throw new NotImplementedException(); |
||||
case Code.Stind_I8: throw new NotImplementedException(); |
||||
case Code.Stind_R4: throw new NotImplementedException(); |
||||
case Code.Stind_R8: throw new NotImplementedException(); |
||||
case Code.Stind_Ref: throw new NotImplementedException(); |
||||
#endregion
|
||||
case Code.Arglist: throw new NotImplementedException(); |
||||
case Code.Box: throw new NotImplementedException(); |
||||
case Code.Break: throw new NotImplementedException(); |
||||
case Code.Call: return ((MethodReference)operand).ReturnType; |
||||
case Code.Calli: throw new NotImplementedException(); |
||||
case Code.Callvirt: return ((MethodReference)operand).ReturnType; |
||||
case Code.Castclass: throw new NotImplementedException(); |
||||
case Code.Ckfinite: throw new NotImplementedException(); |
||||
case Code.Constrained: throw new NotImplementedException(); |
||||
case Code.Cpblk: throw new NotImplementedException(); |
||||
case Code.Cpobj: throw new NotImplementedException(); |
||||
case Code.Dup: throw new NotImplementedException(); |
||||
case Code.Endfilter: throw new NotImplementedException(); |
||||
case Code.Endfinally: throw new NotImplementedException(); |
||||
case Code.Initblk: throw new NotImplementedException(); |
||||
case Code.Initobj: throw new NotImplementedException(); |
||||
case Code.Isinst: throw new NotImplementedException(); |
||||
case Code.Jmp: throw new NotImplementedException(); |
||||
case Code.Ldarg: |
||||
TypeReference typeRef = ((ParameterDefinition)operand).ParameterType; |
||||
// 'this' returns null; TODO: Return proper type of this
|
||||
return typeRef ?? TypeObject; |
||||
case Code.Ldarga: throw new NotImplementedException(); |
||||
case Code.Ldc_I4: |
||||
if ((int)operand == 0) { |
||||
return TypeZero; |
||||
} else if ((int)operand == 1) { |
||||
return TypeOne; |
||||
} else { |
||||
return TypeInt32; |
||||
} |
||||
case Code.Ldc_I8: throw new NotImplementedException(); |
||||
case Code.Ldc_R4: throw new NotImplementedException(); |
||||
case Code.Ldc_R8: throw new NotImplementedException(); |
||||
case Code.Ldfld: return ((FieldDefinition)operand).FieldType; |
||||
case Code.Ldflda: throw new NotImplementedException(); |
||||
case Code.Ldftn: throw new NotImplementedException(); |
||||
case Code.Ldloc: return ((VariableDefinition)operand).VariableType; |
||||
case Code.Ldloca: throw new NotImplementedException(); |
||||
case Code.Ldnull: throw new NotImplementedException(); |
||||
case Code.Ldobj: throw new NotImplementedException(); |
||||
case Code.Ldsfld: throw new NotImplementedException(); |
||||
case Code.Ldsflda: throw new NotImplementedException(); |
||||
case Code.Ldstr: return TypeString; |
||||
case Code.Ldtoken: throw new NotImplementedException(); |
||||
case Code.Ldvirtftn: throw new NotImplementedException(); |
||||
case Code.Leave: throw new NotImplementedException(); |
||||
case Code.Localloc: throw new NotImplementedException(); |
||||
case Code.Mkrefany: throw new NotImplementedException(); |
||||
case Code.Newobj: throw new NotImplementedException(); |
||||
case Code.No: throw new NotImplementedException(); |
||||
case Code.Nop: return TypeVoid; |
||||
case Code.Or: throw new NotImplementedException(); |
||||
case Code.Pop: throw new NotImplementedException(); |
||||
case Code.Readonly: throw new NotImplementedException(); |
||||
case Code.Refanytype: throw new NotImplementedException(); |
||||
case Code.Refanyval: throw new NotImplementedException(); |
||||
case Code.Ret: return TypeVoid; |
||||
case Code.Rethrow: throw new NotImplementedException(); |
||||
case Code.Sizeof: throw new NotImplementedException(); |
||||
case Code.Starg: throw new NotImplementedException(); |
||||
case Code.Stfld: throw new NotImplementedException(); |
||||
case Code.Stloc: return TypeVoid; |
||||
case Code.Stobj: throw new NotImplementedException(); |
||||
case Code.Stsfld: throw new NotImplementedException(); |
||||
case Code.Switch: throw new NotImplementedException(); |
||||
case Code.Tail: throw new NotImplementedException(); |
||||
case Code.Throw: throw new NotImplementedException(); |
||||
case Code.Unaligned: throw new NotImplementedException(); |
||||
case Code.Unbox: throw new NotImplementedException(); |
||||
case Code.Unbox_Any: throw new NotImplementedException(); |
||||
case Code.Volatile: throw new NotImplementedException(); |
||||
default: throw new Exception("Unknown OpCode: " + opCode); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,41 @@
@@ -0,0 +1,41 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
|
||||
public static class DelegateConstruction |
||||
{ |
||||
public static void Test(this string a) |
||||
{ |
||||
} |
||||
|
||||
public static Action<string> ExtensionMethodUnbound() |
||||
{ |
||||
return new Action<string>(DelegateConstruction.Test); |
||||
} |
||||
|
||||
public static Action ExtensionMethodBound() |
||||
{ |
||||
return new Action("abc".Test); |
||||
} |
||||
|
||||
public static Action ExtensionMethodBoundOnNull() |
||||
{ |
||||
return new Action(((string)null).Test); |
||||
} |
||||
|
||||
public static object StaticMethod() |
||||
{ |
||||
return new Func<Action>(DelegateConstruction.ExtensionMethodBound); |
||||
} |
||||
|
||||
public static object InstanceMethod() |
||||
{ |
||||
return new Func<string>("hello".ToUpper); |
||||
} |
||||
|
||||
public static object InstanceMethodOnNull() |
||||
{ |
||||
return new Func<string>(((string)null).ToUpper); |
||||
} |
||||
} |
||||
@ -0,0 +1,66 @@
@@ -0,0 +1,66 @@
|
||||
<?xml version="1.0" encoding="utf-8"?> |
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build"> |
||||
<PropertyGroup> |
||||
<ProjectGuid>{FEC0DA52-C4A6-4710-BE36-B484A20C5E22}</ProjectGuid> |
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> |
||||
<Platform Condition=" '$(Platform)' == '' ">x86</Platform> |
||||
<OutputType>Exe</OutputType> |
||||
<RootNamespace>ICSharpCode.Decompiler.Tests</RootNamespace> |
||||
<AssemblyName>ICSharpCode.Decompiler.Tests</AssemblyName> |
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> |
||||
<AppDesignerFolder>Properties</AppDesignerFolder> |
||||
<AllowUnsafeBlocks>False</AllowUnsafeBlocks> |
||||
<NoStdLib>False</NoStdLib> |
||||
<WarningLevel>4</WarningLevel> |
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Platform)' == 'x86' "> |
||||
<PlatformTarget>x86</PlatformTarget> |
||||
<RegisterForComInterop>False</RegisterForComInterop> |
||||
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies> |
||||
<BaseAddress>4194304</BaseAddress> |
||||
<FileAlignment>4096</FileAlignment> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> |
||||
<OutputPath>..\bin\Debug\</OutputPath> |
||||
<DebugSymbols>true</DebugSymbols> |
||||
<DebugType>Full</DebugType> |
||||
<Optimize>False</Optimize> |
||||
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> |
||||
<DefineConstants>DEBUG;TRACE</DefineConstants> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> |
||||
<OutputPath>..\bin\Release\</OutputPath> |
||||
<DebugSymbols>false</DebugSymbols> |
||||
<DebugType>None</DebugType> |
||||
<Optimize>True</Optimize> |
||||
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> |
||||
<DefineConstants>TRACE</DefineConstants> |
||||
</PropertyGroup> |
||||
<ItemGroup> |
||||
<Reference Include="System" /> |
||||
<Reference Include="System.Core"> |
||||
<RequiredTargetFramework>3.5</RequiredTargetFramework> |
||||
</Reference> |
||||
<Reference Include="System.Xml" /> |
||||
<Reference Include="System.Xml.Linq"> |
||||
<RequiredTargetFramework>3.5</RequiredTargetFramework> |
||||
</Reference> |
||||
</ItemGroup> |
||||
<ItemGroup> |
||||
<Compile Include="DelegateConstruction.cs" /> |
||||
<Compile Include="Loops.cs" /> |
||||
<Compile Include="TestRunner.cs" /> |
||||
</ItemGroup> |
||||
<ItemGroup> |
||||
<ProjectReference Include="..\..\Mono.Cecil\Mono.Cecil.csproj"> |
||||
<Project>{D68133BD-1E63-496E-9EDE-4FBDBF77B486}</Project> |
||||
<Name>Mono.Cecil</Name> |
||||
</ProjectReference> |
||||
<ProjectReference Include="..\ICSharpCode.Decompiler.csproj"> |
||||
<Project>{984CC812-9470-4A13-AFF9-CC44068D666C}</Project> |
||||
<Name>ICSharpCode.Decompiler</Name> |
||||
</ProjectReference> |
||||
</ItemGroup> |
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" /> |
||||
</Project> |
||||
@ -0,0 +1,30 @@
@@ -0,0 +1,30 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
public class Loops |
||||
{ |
||||
public void ForEach(IEnumerable<string> enumerable) |
||||
{ |
||||
foreach (string text in enumerable) { |
||||
text.ToLower(); |
||||
} |
||||
} |
||||
|
||||
public void ForEachOverArray(string[] array) |
||||
{ |
||||
foreach (string text in array) { |
||||
text.ToLower(); |
||||
} |
||||
} |
||||
|
||||
public void ForOverArray(string[] array) |
||||
{ |
||||
for (int i = 0; i < array.Length; i++) { |
||||
array[i].ToLower(); |
||||
} |
||||
} |
||||
} |
||||
|
||||
@ -0,0 +1,101 @@
@@ -0,0 +1,101 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.CodeDom.Compiler; |
||||
using System.Collections.Generic; |
||||
using System.IO; |
||||
using System.Text; |
||||
using Decompiler; |
||||
using Microsoft.CSharp; |
||||
using Mono.Cecil; |
||||
|
||||
namespace ICSharpCode.Decompiler.Tests |
||||
{ |
||||
public class TestRunner |
||||
{ |
||||
public static void Main() |
||||
{ |
||||
Test(@"..\..\Tests\DelegateConstruction.cs"); |
||||
|
||||
Console.ReadKey(); |
||||
} |
||||
|
||||
|
||||
|
||||
static void Test(string fileName) |
||||
{ |
||||
string code = File.ReadAllText(fileName); |
||||
AssemblyDefinition assembly = Compile(code); |
||||
AstBuilder decompiler = new AstBuilder(new DecompilerContext()); |
||||
decompiler.AddAssembly(assembly); |
||||
StringWriter output = new StringWriter(); |
||||
decompiler.GenerateCode(new PlainTextOutput(output)); |
||||
StringWriter diff = new StringWriter(); |
||||
if (!Compare(code, output.ToString(), diff)) { |
||||
throw new Exception("Test failure." + Environment.NewLine + diff.ToString()); |
||||
} |
||||
} |
||||
|
||||
static bool Compare(string input1, string input2, StringWriter diff) |
||||
{ |
||||
bool ok = true; |
||||
int numberOfContinuousMistakes = 0; |
||||
StringReader r1 = new StringReader(input1); |
||||
StringReader r2 = new StringReader(input2); |
||||
string line1, line2; |
||||
while ((line1 = r1.ReadLine()) != null) { |
||||
string trimmed = line1.Trim(); |
||||
if (trimmed.Length == 0 || trimmed.StartsWith("//", StringComparison.Ordinal) || line1.StartsWith("using ", StringComparison.Ordinal)) { |
||||
diff.WriteLine(" " + line1); |
||||
continue; |
||||
} |
||||
line2 = r2.ReadLine(); |
||||
while (line2 != null && (line2.StartsWith("using ", StringComparison.Ordinal) || line2.Trim().Length == 0)) |
||||
line2 = r2.ReadLine(); |
||||
if (line2 == null) { |
||||
ok = false; |
||||
diff.WriteLine("-" + line1); |
||||
continue; |
||||
} |
||||
if (line1 != line2) { |
||||
ok = false; |
||||
if (numberOfContinuousMistakes++ > 5) |
||||
return false; |
||||
diff.WriteLine("-" + line1); |
||||
diff.WriteLine("+" + line2); |
||||
} else { |
||||
if (numberOfContinuousMistakes > 0) |
||||
numberOfContinuousMistakes--; |
||||
diff.WriteLine(" " + line1); |
||||
} |
||||
} |
||||
while ((line2 = r2.ReadLine()) != null) { |
||||
ok = false; |
||||
diff.WriteLine("+" + line1); |
||||
} |
||||
return ok; |
||||
} |
||||
|
||||
static AssemblyDefinition Compile(string code) |
||||
{ |
||||
CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string> {{ "CompilerVersion", "v4.0" }}); |
||||
CompilerParameters options = new CompilerParameters(); |
||||
options.ReferencedAssemblies.Add("System.Core.dll"); |
||||
CompilerResults results = provider.CompileAssemblyFromSource(options, code); |
||||
try { |
||||
if (results.Errors.Count > 0) { |
||||
StringBuilder b = new StringBuilder("Compiler error:"); |
||||
foreach (var error in results.Errors) { |
||||
b.AppendLine(error.ToString()); |
||||
} |
||||
throw new Exception(b.ToString()); |
||||
} |
||||
return AssemblyDefinition.ReadAssembly(results.PathToAssembly); |
||||
} finally { |
||||
File.Delete(results.PathToAssembly); |
||||
results.TempFiles.Delete(); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
@ -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 MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.IO; |
||||
using System.Reflection; |
||||
using System.Windows.Baml2006; |
||||
using System.Xaml; |
||||
using System.Xml; |
||||
|
||||
namespace ICSharpCode.ILSpy |
||||
{ |
||||
/// <remarks>Caution: use in separate AppDomain only!</remarks>
|
||||
public class BamlDecompiler : MarshalByRefObject |
||||
{ |
||||
public BamlDecompiler() |
||||
{ |
||||
} |
||||
|
||||
public string DecompileBaml(MemoryStream bamlCode, string containingAssemblyFile) |
||||
{ |
||||
bamlCode.Position = 0; |
||||
TextWriter w = new StringWriter(); |
||||
|
||||
Assembly assembly = Assembly.LoadFile(containingAssemblyFile); |
||||
|
||||
Baml2006Reader reader = new Baml2006Reader(bamlCode, new XamlReaderSettings() { ValuesMustBeString = true, LocalAssembly = assembly }); |
||||
XamlXmlWriter writer = new XamlXmlWriter(new XmlTextWriter(w) { Formatting = Formatting.Indented }, reader.SchemaContext); |
||||
while (reader.Read()) { |
||||
switch (reader.NodeType) { |
||||
case XamlNodeType.None: |
||||
|
||||
break; |
||||
case XamlNodeType.StartObject: |
||||
writer.WriteStartObject(reader.Type); |
||||
break; |
||||
case XamlNodeType.GetObject: |
||||
writer.WriteGetObject(); |
||||
break; |
||||
case XamlNodeType.EndObject: |
||||
writer.WriteEndObject(); |
||||
break; |
||||
case XamlNodeType.StartMember: |
||||
writer.WriteStartMember(reader.Member); |
||||
break; |
||||
case XamlNodeType.EndMember: |
||||
writer.WriteEndMember(); |
||||
break; |
||||
case XamlNodeType.Value: |
||||
// requires XamlReaderSettings.ValuesMustBeString = true to work properly
|
||||
writer.WriteValue(reader.Value); |
||||
break; |
||||
case XamlNodeType.NamespaceDeclaration: |
||||
writer.WriteNamespace(reader.Namespace); |
||||
break; |
||||
default: |
||||
throw new Exception("Invalid value for XamlNodeType"); |
||||
} |
||||
} |
||||
return w.ToString(); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,122 @@
@@ -0,0 +1,122 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.IO; |
||||
using System.Linq; |
||||
using System.Reflection; |
||||
using System.Threading.Tasks; |
||||
using System.Windows.Controls; |
||||
using System.Windows.Media.Imaging; |
||||
|
||||
using ICSharpCode.AvalonEdit.Highlighting; |
||||
using ICSharpCode.Decompiler; |
||||
using ICSharpCode.ILSpy.TextView; |
||||
using Microsoft.Win32; |
||||
|
||||
namespace ICSharpCode.ILSpy.TreeNodes |
||||
{ |
||||
class ResourceEntryNode : ILSpyTreeNode |
||||
{ |
||||
string key; |
||||
Stream value; |
||||
|
||||
public override object Text { |
||||
get { return key.ToString(); } |
||||
} |
||||
|
||||
public override object Icon { |
||||
get { return Images.Resource; } |
||||
} |
||||
|
||||
public ResourceEntryNode(string key, Stream value) |
||||
{ |
||||
this.key = key; |
||||
this.value = value; |
||||
} |
||||
|
||||
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) |
||||
{ |
||||
language.WriteCommentLine(output, string.Format("{0} = {1}", key, value)); |
||||
} |
||||
|
||||
internal override bool View(DecompilerTextView textView) |
||||
{ |
||||
AvalonEditTextOutput output = new AvalonEditTextOutput(); |
||||
IHighlightingDefinition highlighting = null; |
||||
|
||||
if (LoadImage(output)) { |
||||
textView.Show(output, highlighting); |
||||
} else { |
||||
textView.RunWithCancellation( |
||||
token => Task.Factory.StartNew( |
||||
() => { |
||||
try { |
||||
if (LoadBaml(output)) |
||||
highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); |
||||
} catch (Exception ex) { |
||||
output.Write(ex.ToString()); |
||||
} |
||||
return output; |
||||
}), |
||||
t => textView.Show(t.Result, highlighting) |
||||
); |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
bool LoadImage(AvalonEditTextOutput output) |
||||
{ |
||||
try { |
||||
value.Position = 0; |
||||
BitmapImage image = new BitmapImage(); |
||||
image.BeginInit(); |
||||
image.StreamSource = value; |
||||
image.EndInit(); |
||||
output.AddUIElement(() => new Image { Source = image }); |
||||
output.WriteLine(); |
||||
output.AddButton(Images.Save, "Save", delegate { Save(); }); |
||||
} catch (Exception) { |
||||
return false; |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
bool LoadBaml(AvalonEditTextOutput output) |
||||
{ |
||||
var asm = this.Ancestors().OfType<AssemblyTreeNode>().FirstOrDefault().LoadedAssembly; |
||||
|
||||
// Construct and initialize settings for a second AppDomain.
|
||||
AppDomainSetup bamlDecompilerAppDomainSetup = new AppDomainSetup(); |
||||
bamlDecompilerAppDomainSetup.ApplicationBase = "file:///" + Path.GetDirectoryName(asm.FileName); |
||||
bamlDecompilerAppDomainSetup.DisallowBindingRedirects = false; |
||||
bamlDecompilerAppDomainSetup.DisallowCodeDownload = true; |
||||
bamlDecompilerAppDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; |
||||
|
||||
// Create the second AppDomain.
|
||||
AppDomain bamlDecompilerAppDomain = AppDomain.CreateDomain("BamlDecompiler AD", null, bamlDecompilerAppDomainSetup); |
||||
|
||||
BamlDecompiler decompiler = (BamlDecompiler)bamlDecompilerAppDomain.CreateInstanceFromAndUnwrap(typeof(BamlDecompiler).Assembly.Location, typeof(BamlDecompiler).FullName); |
||||
|
||||
MemoryStream bamlStream = new MemoryStream(); |
||||
value.Position = 0; |
||||
value.CopyTo(bamlStream); |
||||
|
||||
output.Write(decompiler.DecompileBaml(bamlStream, asm.FileName)); |
||||
return true; |
||||
} |
||||
|
||||
public override bool Save() |
||||
{ |
||||
SaveFileDialog dlg = new SaveFileDialog(); |
||||
dlg.FileName = Path.GetFileName(DecompilerTextView.CleanUpName(key)); |
||||
if (dlg.ShowDialog() == true) { |
||||
value.Position = 0; |
||||
using (var fs = dlg.OpenFile()) { |
||||
value.CopyTo(fs); |
||||
} |
||||
} |
||||
return true; |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,156 @@
@@ -0,0 +1,156 @@
|
||||
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
|
||||
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
|
||||
|
||||
using System; |
||||
using System.Collections; |
||||
using System.Collections.Generic; |
||||
using System.Linq; |
||||
|
||||
namespace ICSharpCode.NRefactory.CSharp |
||||
{ |
||||
/// <summary>
|
||||
/// Represents the children of an AstNode that have a specific role.
|
||||
/// </summary>
|
||||
public struct AstNodeCollection<T> : ICollection<T> where T : AstNode |
||||
{ |
||||
readonly AstNode node; |
||||
readonly Role<T> role; |
||||
|
||||
public AstNodeCollection(AstNode node, Role<T> role) |
||||
{ |
||||
if (node == null) |
||||
throw new ArgumentNullException("node"); |
||||
if (role == null) |
||||
throw new ArgumentNullException("role"); |
||||
this.node = node; |
||||
this.role = role; |
||||
} |
||||
|
||||
public int Count { |
||||
get { |
||||
var e = GetEnumerator(); |
||||
int count = 0; |
||||
while (e.MoveNext()) |
||||
count++; |
||||
return count; |
||||
} |
||||
} |
||||
|
||||
public void Add(T element) |
||||
{ |
||||
node.AddChild(element, role); |
||||
} |
||||
|
||||
public void AddRange(IEnumerable<T> nodes) |
||||
{ |
||||
// Evaluate 'nodes' first, since it might change when we add the new children
|
||||
// Example: collection.AddRange(collection);
|
||||
if (nodes != null) { |
||||
foreach (T node in nodes.ToList()) |
||||
Add(node); |
||||
} |
||||
} |
||||
|
||||
public void AddRange(T[] nodes) |
||||
{ |
||||
// Fast overload for arrays - we don't need to create a copy
|
||||
if (nodes != null) { |
||||
foreach (T node in nodes) |
||||
Add(node); |
||||
} |
||||
} |
||||
|
||||
public void ReplaceWith(IEnumerable<T> nodes) |
||||
{ |
||||
// Evaluate 'nodes' first, since it might change when we call Clear()
|
||||
// Example: collection.ReplaceWith(collection);
|
||||
if (nodes != null) |
||||
nodes = nodes.ToList(); |
||||
Clear(); |
||||
foreach (T node in nodes) |
||||
Add(node); |
||||
} |
||||
|
||||
public void MoveTo(ICollection<T> targetCollection) |
||||
{ |
||||
foreach (T node in this) { |
||||
node.Remove(); |
||||
targetCollection.Add(node); |
||||
} |
||||
} |
||||
|
||||
public bool Contains(T element) |
||||
{ |
||||
return element != null && element.Parent == node && element.Role == role; |
||||
} |
||||
|
||||
public bool Remove(T element) |
||||
{ |
||||
if (Contains(element)) { |
||||
element.Remove(); |
||||
return true; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
public void CopyTo(T[] array, int arrayIndex) |
||||
{ |
||||
foreach (T item in this) |
||||
array[arrayIndex++] = item; |
||||
} |
||||
|
||||
public void Clear() |
||||
{ |
||||
foreach (T item in this) |
||||
item.Remove(); |
||||
} |
||||
|
||||
bool ICollection<T>.IsReadOnly { |
||||
get { return false; } |
||||
} |
||||
|
||||
public IEnumerator<T> GetEnumerator() |
||||
{ |
||||
AstNode next; |
||||
for (AstNode cur = node.FirstChild; cur != null; cur = next) { |
||||
// Remember next before yielding cur.
|
||||
// This allows removing/replacing nodes while iterating through the list.
|
||||
next = cur.NextSibling; |
||||
if (cur.Role == role) |
||||
yield return (T)cur; |
||||
} |
||||
} |
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() |
||||
{ |
||||
return GetEnumerator(); |
||||
} |
||||
|
||||
#region Equals and GetHashCode implementation
|
||||
public override bool Equals(object obj) |
||||
{ |
||||
if (obj is AstNodeCollection<T>) { |
||||
return ((AstNodeCollection<T>)obj) == this; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
public override int GetHashCode() |
||||
{ |
||||
return node.GetHashCode() ^ role.GetHashCode(); |
||||
} |
||||
|
||||
public static bool operator ==(AstNodeCollection<T> left, AstNodeCollection<T> right) |
||||
{ |
||||
return left.role == right.role && left.node == right.node; |
||||
} |
||||
|
||||
public static bool operator !=(AstNodeCollection<T> left, AstNodeCollection<T> right) |
||||
{ |
||||
return !(left.role == right.role && left.node == right.node); |
||||
} |
||||
#endregion
|
||||
} |
||||
} |
||||
Loading…
Reference in new issue