11 Commits
Author SHA1 Message Date
ds5678 c8e1b8809c Bump version 2024-09-07 12:50:59 -07:00
ds5678 a0c48e0216 Backing field improvements
* More strict identification
* Add extensions for fields, events, and properties
2024-09-07 12:50:18 -07:00
ds5678 1df36de7df Field extensions 2024-09-01 08:21:39 -07:00
ds5678 89d8b4a7cd Event and property extensions 2024-09-01 08:15:23 -07:00
ds5678 9106df0c05 Version bump 2024-07-25 07:33:21 -07:00
ds5678 7f4f811679 More extensions 2024-07-25 07:32:35 -07:00
ds5678 2085e5f81e For standardization, don't replace br false with br true 2024-07-21 10:58:12 -07:00
ds5678 5806496459 Handle switch instructions for macro standardization 2024-07-21 10:55:38 -07:00
ds5678 ecdd481b87 Add assembly validator project 2024-07-12 20:32:22 -07:00
ds5678 2e4fa07015 MacroStandardization 2024-07-09 23:35:26 -07:00
ds5678 995d4d5e05 Add more extension methods 2024-07-06 13:07:57 -04:00
13 changed files with 882 additions and 44 deletions

No files matched your search

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AssetRipper.CIL\AssetRipper.CIL.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,151 @@
using AsmResolver.DotNet;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Cil;
namespace AssetRipper.CIL.Validator;
public static class CilInstructionCollectionEquality
{
public static bool Equals(CilMethodBody left, CilMethodBody right)
{
if (left.LocalVariables.Count != right.LocalVariables.Count)
{
return false;
}
for (int i = 0; i < left.LocalVariables.Count; i++)
{
if (!SignatureComparer.Default.Equals(left.LocalVariables[i].VariableType, right.LocalVariables[i].VariableType))
{
return false;
}
}
return Equals(left.Instructions, right.Instructions);
}
public static bool Equals(CilInstructionCollection left, CilInstructionCollection right)
{
if (left.Count != right.Count)
{
return false;
}
for (int i = 0; i < left.Count; i++)
{
CilInstruction leftInstruction = left[i];
CilInstruction rightInstruction = right[i];
if (leftInstruction.OpCode != rightInstruction.OpCode || leftInstruction.Operand?.GetType() != rightInstruction.Operand?.GetType())
{
return false;
}
if (rightInstruction.Operand is null)
{
// Both operands are null because of the type check.
continue;
}
switch (leftInstruction.Operand)
{
case CilInstructionLabel leftLabel:
{
CilInstructionLabel rightLabel = (CilInstructionLabel)rightInstruction.Operand;
int leftIndex = leftLabel.Instruction is null ? -1 : left.IndexOf(leftLabel.Instruction);
int rightIndex = rightLabel.Instruction is null ? -1 : right.IndexOf(rightLabel.Instruction);
if (leftIndex != rightIndex)
{
return false;
}
}
break;
case CilInstructionLabel[] leftLabels:
{
CilInstructionLabel[] rightLabels = (CilInstructionLabel[])rightInstruction.Operand;
if (leftLabels.Length != rightLabels.Length)
{
return false;
}
for (int j = 0; j < leftLabels.Length; j++)
{
CilInstructionLabel leftLabel = leftLabels[j];
CilInstructionLabel rightLabel = rightLabels[j];
int leftIndex = leftLabel.Instruction is null ? -1 : left.IndexOf(leftLabel.Instruction);
int rightIndex = rightLabel.Instruction is null ? -1 : right.IndexOf(rightLabel.Instruction);
if (leftIndex != rightIndex)
{
return false;
}
}
}
break;
case Parameter leftParameter:
{
Parameter rightParameter = (Parameter)rightInstruction.Operand;
if (leftParameter.Index != rightParameter.Index)
{
return false;
}
}
break;
case CilLocalVariable leftVariable:
{
CilLocalVariable rightVariable = (CilLocalVariable)rightInstruction.Operand;
if (left.Owner.LocalVariables.IndexOf(leftVariable) != right.Owner.LocalVariables.IndexOf(rightVariable))
{
return false;
}
}
break;
case MemberReference leftMember:
{
MemberReference rightMember = (MemberReference)rightInstruction.Operand;
if (!SignatureComparer.Default.Equals(leftMember, rightMember))
{
return false;
}
}
break;
case IFieldDescriptor leftField:
{
IFieldDescriptor rightField = (IFieldDescriptor)rightInstruction.Operand;
if (!SignatureComparer.Default.Equals(leftField, rightField))
{
return false;
}
}
break;
case ITypeDefOrRef leftType:
{
ITypeDefOrRef rightType = (ITypeDefOrRef)rightInstruction.Operand;
if (!SignatureComparer.Default.Equals(leftType, rightType))
{
return false;
}
}
break;
case IMethodDescriptor leftMethod:
{
IMethodDescriptor rightMethod = (IMethodDescriptor)rightInstruction.Operand;
if (!SignatureComparer.Default.Equals(leftMethod, rightMethod))
{
return false;
}
}
break;
default:
if (!leftInstruction.Operand!.Equals(rightInstruction.Operand))
{
return false;
}
break;
}
}
return true;
}
}
+236
View File
@@ -0,0 +1,236 @@
using AsmResolver.DotNet;
using AsmResolver.DotNet.Signatures;
namespace AssetRipper.CIL.Validator;
internal class Program
{
static void Main(string[] args)
{
ModuleDefinition module1 = ModuleDefinition.FromFile(args[0]);
ModuleDefinition module2 = ModuleDefinition.FromFile(args[1]);
List<TypeDefinition> typesMissingFrom1 = new();
List<TypeDefinition> typesMissingFrom2 = new();
Dictionary<TypeDefinition, TypeDefinition> type1ToType2 = new();
MatchTypes(module1, module2, typesMissingFrom1, typesMissingFrom2, type1ToType2);
List<MethodDefinition> methodsMissingFrom1 = new();
List<MethodDefinition> methodsMissingFrom2 = new();
Dictionary<MethodDefinition, MethodDefinition> method1ToMethod2 = new();
foreach ((TypeDefinition type1, TypeDefinition type2) in type1ToType2)
{
MatchNameAndSignature(type1.Methods, type2.Methods, methodsMissingFrom1, methodsMissingFrom2, method1ToMethod2, m => m.Signature!, SignatureComparer.Default);
}
List<(MethodDefinition, MethodDefinition)> differentMethods = new();
foreach ((MethodDefinition method1, MethodDefinition method2) in method1ToMethod2)
{
if (method1.CilMethodBody is null)
{
if (method2.CilMethodBody is not null)
{
differentMethods.Add((method1, method2));
}
continue;
}
else if (method2.CilMethodBody is null)
{
differentMethods.Add((method1, method2));
continue;
}
method1.CilMethodBody.Instructions.ExpandMacros();
method2.CilMethodBody.Instructions.ExpandMacros();
if (!CilInstructionCollectionEquality.Equals(method1.CilMethodBody, method2.CilMethodBody))
{
CilInstructionCollectionEquality.Equals(method1.CilMethodBody, method2.CilMethodBody);
differentMethods.Add((method1, method2));
}
}
List<FieldDefinition> fieldsMissingFrom1 = new();
List<FieldDefinition> fieldsMissingFrom2 = new();
Dictionary<FieldDefinition, FieldDefinition> field1ToField2 = new();
foreach ((TypeDefinition type1, TypeDefinition type2) in type1ToType2)
{
MatchName(type1.Fields, type2.Fields, fieldsMissingFrom1, fieldsMissingFrom2, field1ToField2);
}
List<(FieldDefinition, FieldDefinition)> differentFields = new();
foreach ((FieldDefinition field1, FieldDefinition field2) in field1ToField2)
{
if (!SignatureComparer.Default.Equals(field1.Signature, field2.Signature))
{
differentFields.Add((field1, field2));
}
}
List<PropertyDefinition> propertiesMissingFrom1 = new();
List<PropertyDefinition> propertiesMissingFrom2 = new();
Dictionary<PropertyDefinition, PropertyDefinition> property1ToProperty2 = new();
foreach ((TypeDefinition type1, TypeDefinition type2) in type1ToType2)
{
MatchNameAndSignature(type1.Properties, type2.Properties, propertiesMissingFrom1, propertiesMissingFrom2, property1ToProperty2, p => p.Signature!, SignatureComparer.Default);
}
List<EventDefinition> eventsMissingFrom1 = new();
List<EventDefinition> eventsMissingFrom2 = new();
Dictionary<EventDefinition, EventDefinition> event1ToEvent2 = new();
foreach ((TypeDefinition type1, TypeDefinition type2) in type1ToType2)
{
MatchName(type1.Events, type2.Events, eventsMissingFrom1, eventsMissingFrom2, event1ToEvent2);
}
List<(EventDefinition, EventDefinition)> differentEvents = new();
foreach ((EventDefinition event1, EventDefinition event2) in event1ToEvent2)
{
if (!SignatureComparer.Default.Equals(event1.EventType, event2.EventType))
{
differentEvents.Add((event1, event2));
}
}
Console.WriteLine($"Types missing from module 1: {typesMissingFrom1.Count}");
Console.WriteLine($"Types missing from module 2: {typesMissingFrom2.Count}");
Console.WriteLine($"Types matched: {type1ToType2.Count}");
Console.WriteLine();
Console.WriteLine($"Methods missing from module 1: {methodsMissingFrom1.Count}");
Console.WriteLine($"Methods missing from module 2: {methodsMissingFrom2.Count}");
Console.WriteLine($"Methods matched: {method1ToMethod2.Count}");
Console.WriteLine($"Different methods: {differentMethods.Count}");
Console.WriteLine();
Console.WriteLine($"Fields missing from module 1: {fieldsMissingFrom1.Count}");
Console.WriteLine($"Fields missing from module 2: {fieldsMissingFrom2.Count}");
Console.WriteLine($"Fields matched: {field1ToField2.Count}");
Console.WriteLine($"Different fields: {differentFields.Count}");
Console.WriteLine();
Console.WriteLine($"Properties missing from module 1: {propertiesMissingFrom1.Count}");
Console.WriteLine($"Properties missing from module 2: {propertiesMissingFrom2.Count}");
Console.WriteLine($"Properties matched: {property1ToProperty2.Count}");
Console.WriteLine();
Console.WriteLine($"Events missing from module 1: {eventsMissingFrom1.Count}");
Console.WriteLine($"Events missing from module 2: {eventsMissingFrom2.Count}");
Console.WriteLine($"Events matched: {event1ToEvent2.Count}");
Console.WriteLine($"Different events: {differentEvents.Count}");
}
private static void MatchName<T>(IList<T> list1, IList<T> list2, List<T> missingFrom1, List<T> missingFrom2, Dictionary<T, T> value1ToValue2)
where T : class, INameProvider
{
for (int i = 0; i < list2.Count; i++)
{
T value2 = list2[i];
if (i < list1.Count && list1[i].Name == value2.Name)
{
value1ToValue2.Add(list1[i], value2);
continue;
}
T? value1 = list1.FirstOrDefault(v => v.Name == value2.Name);
if (value1 is null)
{
missingFrom1.Add(value2);
}
else
{
value1ToValue2.Add(value1, value2);
}
}
foreach (T value1 in list1)
{
if (!value1ToValue2.ContainsKey(value1))
{
missingFrom2.Add(value1);
}
}
}
private static void MatchNameAndSignature<T, TSignature>(IList<T> list1, IList<T> list2, List<T> missingFrom1, List<T> missingFrom2, Dictionary<T, T> value1ToValue2, Func<T, TSignature> getSignature, IEqualityComparer<TSignature> signatureComparer)
where T : class, INameProvider
{
for (int i = 0; i < list2.Count; i++)
{
T value2 = list2[i];
if (i < list1.Count && list1[i].Name == value2.Name && SignatureEquals(list1[i], value2, getSignature, signatureComparer))
{
value1ToValue2.Add(list1[i], value2);
continue;
}
T? value1 = list1.FirstOrDefault(v => v.Name == value2.Name && SignatureEquals(v, value2, getSignature, signatureComparer));
if (value1 is null)
{
missingFrom1.Add(value2);
}
else
{
value1ToValue2.Add(value1, value2);
}
}
foreach (T value1 in list1)
{
if (!value1ToValue2.ContainsKey(value1))
{
missingFrom2.Add(value1);
}
}
static bool SignatureEquals(T value1, T value2, Func<T, TSignature> getSignature, IEqualityComparer<TSignature> signatureComparer)
{
return signatureComparer.Equals(getSignature(value1), getSignature(value2));
}
}
private static void MatchTypes(ModuleDefinition module1, ModuleDefinition module2, List<TypeDefinition> typesMissingFrom1, List<TypeDefinition> typesMissingFrom2, Dictionary<TypeDefinition, TypeDefinition> type1ToType2)
{
foreach (TypeDefinition type2 in module2.TopLevelTypes)
{
TypeDefinition? type1 = module1.TopLevelTypes.FirstOrDefault(t => SignatureComparer.Default.Equals(t, type2));
if (type1 is null)
{
typesMissingFrom1.Add(type2);
}
else
{
type1ToType2.Add(type1, type2);
MatchNestedTypes(type1, type2, typesMissingFrom1, typesMissingFrom2, type1ToType2);
}
}
foreach (TypeDefinition type1 in module1.TopLevelTypes)
{
if (!type1ToType2.ContainsKey(type1))
{
typesMissingFrom2.Add(type1);
}
}
static void MatchNestedTypes(TypeDefinition type1, TypeDefinition type2, List<TypeDefinition> typesMissingFrom1, List<TypeDefinition> typesMissingFrom2, Dictionary<TypeDefinition, TypeDefinition> type1ToType2)
{
foreach (TypeDefinition nestedType2 in type2.NestedTypes)
{
TypeDefinition? nestedType1 = type1.NestedTypes.FirstOrDefault(t => t.Name == nestedType2.Name);
if (nestedType1 is null)
{
typesMissingFrom1.Add(nestedType2);
}
else
{
type1ToType2.Add(nestedType1, nestedType2);
MatchNestedTypes(nestedType1, nestedType2, typesMissingFrom1, typesMissingFrom2, type1ToType2);
}
}
foreach (TypeDefinition nestedType1 in type1.NestedTypes)
{
if (!type1ToType2.ContainsKey(nestedType1))
{
typesMissingFrom2.Add(nestedType1);
}
}
}
}
}
+40 -34
View File
@@ -1,34 +1,40 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34321.82
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AssetRipper.CIL", "AssetRipper.CIL\AssetRipper.CIL.csproj", "{3F385513-F04F-4282-9B91-2693CA93ED1C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{88415A5B-37C1-4CDF-93E0-2682460B6390}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
.gitignore = .gitignore
Directory.Build.props = Directory.Build.props
LICENSE = LICENSE
README.md = README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3F385513-F04F-4282-9B91-2693CA93ED1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3F385513-F04F-4282-9B91-2693CA93ED1C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3F385513-F04F-4282-9B91-2693CA93ED1C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3F385513-F04F-4282-9B91-2693CA93ED1C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FEAD0DEB-0A49-4BC9-A468-3D1E9D52EF2C}
EndGlobalSection
EndGlobal
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34321.82
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AssetRipper.CIL", "AssetRipper.CIL\AssetRipper.CIL.csproj", "{3F385513-F04F-4282-9B91-2693CA93ED1C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{88415A5B-37C1-4CDF-93E0-2682460B6390}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
.gitignore = .gitignore
Directory.Build.props = Directory.Build.props
LICENSE = LICENSE
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AssetRipper.CIL.Validator", "AssetRipper.CIL.Validator\AssetRipper.CIL.Validator.csproj", "{0E177F49-031D-486A-ADD2-6823263D1923}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3F385513-F04F-4282-9B91-2693CA93ED1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3F385513-F04F-4282-9B91-2693CA93ED1C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3F385513-F04F-4282-9B91-2693CA93ED1C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3F385513-F04F-4282-9B91-2693CA93ED1C}.Release|Any CPU.Build.0 = Release|Any CPU
{0E177F49-031D-486A-ADD2-6823263D1923}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0E177F49-031D-486A-ADD2-6823263D1923}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0E177F49-031D-486A-ADD2-6823263D1923}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0E177F49-031D-486A-ADD2-6823263D1923}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FEAD0DEB-0A49-4BC9-A468-3D1E9D52EF2C}
EndGlobalSection
EndGlobal
@@ -36,12 +36,41 @@ public static class CilInstructionCollectionExtensions
}
}
public static void InitializeDefaultValue(this CilInstructionCollection instructions, CilLocalVariable localVariable)
{
TypeSignature type = localVariable.VariableType;
if (type is CorLibTypeSignature { IsValueType: true } corLibTypeSignature)
{
instructions.InitializeDefaultPrimitiveValue(corLibTypeSignature, localVariable);
}
else if (type is ByReferenceTypeSignature)
{
instructions.AddNullRef();
instructions.Add(CilOpCodes.Stloc, localVariable);
}
else if (type.IsValueTypeOrGenericParameter())
{
instructions.InitializeDefaultValueForUnknownType(localVariable);
}
else
{
instructions.Add(CilOpCodes.Ldnull);
instructions.Add(CilOpCodes.Stloc, localVariable);
}
}
/// <summary>
/// Remove the last instruction in the collection
/// </summary>
/// <param name="instructions">The collection to remove the instruction from</param>
public static void Pop(this CilInstructionCollection instructions) => instructions.RemoveAt(instructions.Count - 1);
public static void AddBooleanNot(this CilInstructionCollection instructions)
{
instructions.Add(CilOpCodes.Ldc_I4_0);
instructions.Add(CilOpCodes.Ceq);
}
public static CilInstruction AddLoadElement(this CilInstructionCollection instructions, TypeSignature elementType)
{
return elementType switch
@@ -90,6 +119,52 @@ public static class CilInstructionCollectionExtensions
};
}
public static CilInstruction AddLoadIndirect(this CilInstructionCollection instructions, TypeSignature type)
{
return type switch
{
CorLibTypeSignature corLibTypeSignature => corLibTypeSignature.ElementType switch
{
ElementType.I1 => instructions.Add(CilOpCodes.Ldind_I1),
ElementType.I2 => instructions.Add(CilOpCodes.Ldind_I2),
ElementType.I4 => instructions.Add(CilOpCodes.Ldind_I4),
ElementType.I8 or ElementType.U8 => instructions.Add(CilOpCodes.Ldind_I8),
ElementType.U1 => instructions.Add(CilOpCodes.Ldind_U1),
ElementType.U2 => instructions.Add(CilOpCodes.Ldind_U2),
ElementType.U4 => instructions.Add(CilOpCodes.Ldind_U4),
ElementType.R4 => instructions.Add(CilOpCodes.Ldind_R4),
ElementType.R8 => instructions.Add(CilOpCodes.Ldind_R8),
ElementType.I or ElementType.U => instructions.Add(CilOpCodes.Ldind_I),
_ => instructions.Add(CilOpCodes.Ldobj, type.ToTypeDefOrRef()),
},
PointerTypeSignature => instructions.Add(CilOpCodes.Ldind_I),
_ => instructions.Add(CilOpCodes.Ldobj, type.ToTypeDefOrRef()),
};
}
public static CilInstruction AddStoreIndirect(this CilInstructionCollection instructions, TypeSignature type)
{
return type switch
{
CorLibTypeSignature corLibTypeSignature => corLibTypeSignature.ElementType switch
{
ElementType.I1 => instructions.Add(CilOpCodes.Stind_I1),
ElementType.I2 => instructions.Add(CilOpCodes.Stind_I2),
ElementType.I4 => instructions.Add(CilOpCodes.Stind_I4),
ElementType.I8 or ElementType.U8 => instructions.Add(CilOpCodes.Stind_I8),
ElementType.U1 => instructions.Add(CilOpCodes.Stind_I1),
ElementType.U2 => instructions.Add(CilOpCodes.Stind_I2),
ElementType.U4 => instructions.Add(CilOpCodes.Stind_I4),
ElementType.R4 => instructions.Add(CilOpCodes.Stind_R4),
ElementType.R8 => instructions.Add(CilOpCodes.Stind_R8),
ElementType.I or ElementType.U => instructions.Add(CilOpCodes.Stind_I),
_ => instructions.Add(CilOpCodes.Stobj, type.ToTypeDefOrRef()),
},
PointerTypeSignature => instructions.Add(CilOpCodes.Stind_I),
_ => instructions.Add(CilOpCodes.Stobj, type.ToTypeDefOrRef()),
};
}
/// <summary>
/// Load a null reference onto the stack.
/// </summary>
@@ -116,13 +191,19 @@ public static class CilInstructionCollectionExtensions
/// <param name="type"></param>
private static void AddDefaultValueForUnknownType(this CilInstructionCollection instructions, TypeSignature type)
{
Debug.Assert(type is not CorLibTypeSignature { ElementType: ElementType.Void } and not ByReferenceTypeSignature);
CilLocalVariable variable = instructions.AddLocalVariable(type);
instructions.Add(CilOpCodes.Ldloca, variable);
instructions.Add(CilOpCodes.Initobj, type.ToTypeDefOrRef());
InitializeDefaultValueForUnknownType(instructions, variable);
instructions.Add(CilOpCodes.Ldloc, variable);
}
private static void InitializeDefaultValueForUnknownType(this CilInstructionCollection instructions, CilLocalVariable localVariable)
{
TypeSignature type = localVariable.VariableType;
Debug.Assert(type is not CorLibTypeSignature { ElementType: ElementType.Void } and not ByReferenceTypeSignature);
instructions.Add(CilOpCodes.Ldloca, localVariable);
instructions.Add(CilOpCodes.Initobj, type.ToTypeDefOrRef());
}
private static void AddDefaultPrimitiveValue(this CilInstructionCollection instructions, CorLibTypeSignature type)
{
switch (type.ElementType)
@@ -158,10 +239,58 @@ public static class CilInstructionCollectionExtensions
instructions.Add(CilOpCodes.Ldnull);
break;
case ElementType.TypedByRef:
default:
instructions.AddDefaultValueForUnknownType(type);
break;
}
}
private static void InitializeDefaultPrimitiveValue(this CilInstructionCollection instructions, CorLibTypeSignature type, CilLocalVariable localVariable)
{
switch (type.ElementType)
{
case ElementType.Void:
break;
case ElementType.U1 or ElementType.U2 or ElementType.U4 or ElementType.I1 or ElementType.I2 or ElementType.I4 or ElementType.Boolean or ElementType.Char:
instructions.Add(CilOpCodes.Ldc_I4_0);
instructions.Add(CilOpCodes.Stloc, localVariable);
break;
case ElementType.I8:
instructions.Add(CilOpCodes.Ldc_I4_0);
instructions.Add(CilOpCodes.Conv_I8);
instructions.Add(CilOpCodes.Stloc, localVariable);
break;
case ElementType.U8:
instructions.Add(CilOpCodes.Ldc_I4_0);
instructions.Add(CilOpCodes.Conv_U8);
instructions.Add(CilOpCodes.Stloc, localVariable);
break;
case ElementType.I:
instructions.Add(CilOpCodes.Ldc_I4_0);
instructions.Add(CilOpCodes.Conv_I);
instructions.Add(CilOpCodes.Stloc, localVariable);
break;
case ElementType.U:
instructions.Add(CilOpCodes.Ldc_I4_0);
instructions.Add(CilOpCodes.Conv_U);
instructions.Add(CilOpCodes.Stloc, localVariable);
break;
case ElementType.R4:
instructions.Add(CilOpCodes.Ldc_R4, 0f);
instructions.Add(CilOpCodes.Stloc, localVariable);
break;
case ElementType.R8:
instructions.Add(CilOpCodes.Ldc_R8, 0d);
instructions.Add(CilOpCodes.Stloc, localVariable);
break;
case ElementType.Object or ElementType.String:
instructions.Add(CilOpCodes.Ldnull);
instructions.Add(CilOpCodes.Stloc, localVariable);
break;
case ElementType.TypedByRef:
default:
throw new ArgumentOutOfRangeException(null);
instructions.InitializeDefaultValueForUnknownType(localVariable);
break;
}
}
}
@@ -0,0 +1,53 @@
using AsmResolver.PE.DotNet.Cil;
namespace AssetRipper.CIL;
public static class CilInstructionExtensions
{
public static bool IsLdcI4OrI8(this CilInstruction instruction, out long value)
{
if (instruction.IsLdcI4())
{
value = instruction.GetLdcI4Constant();
return true;
}
else if (instruction.OpCode == CilOpCodes.Ldc_I8 && instruction.Operand is long i64)
{
value = i64;
return true;
}
else
{
value = default;
return false;
}
}
public static bool IsLdcI4(this CilInstruction instruction, out int value)
{
if (instruction.IsLdcI4())
{
value = instruction.GetLdcI4Constant();
return true;
}
else
{
value = default;
return false;
}
}
public static bool IsLdcI8(this CilInstruction instruction, out long value)
{
if (instruction.OpCode == CilOpCodes.Ldc_I8 && instruction.Operand is long i64)
{
value = i64;
return true;
}
else
{
value = default;
return false;
}
}
}
@@ -0,0 +1,53 @@
using AsmResolver.DotNet;
using AsmResolver.DotNet.Signatures;
namespace AssetRipper.CIL;
public static class EventDefinitionExtensions
{
public static bool IsInstance(this EventDefinition eventDefinition)
{
return (eventDefinition.AddMethod?.IsInstance() ?? false)
|| (eventDefinition.RemoveMethod?.IsInstance() ?? false);
}
public static bool IsStatic(this EventDefinition eventDefinition)
{
return (eventDefinition.AddMethod?.IsStatic ?? false)
|| (eventDefinition.RemoveMethod?.IsStatic ?? false);
}
public static bool HasAddMethod(this EventDefinition eventDefinition)
{
return eventDefinition.AddMethod is not null;
}
public static bool HasRemoveMethod(this EventDefinition eventDefinition)
{
return eventDefinition.RemoveMethod is not null;
}
public static bool HasFireMethod(this EventDefinition eventDefinition)
{
return eventDefinition.FireMethod is not null;
}
public static bool HasBackingField(this EventDefinition eventDefinition, out FieldDefinition? backingField)
{
TypeSignature? eventType = eventDefinition.EventType?.ToTypeSignature();
if (eventType is not null)
{
foreach (FieldDefinition field in eventDefinition.DeclaringType?.Fields ?? [])
{
if (field.IsPrivate && field.Name == eventDefinition.Name && SignatureComparer.Default.Equals(field.Signature?.FieldType, eventType))
{
backingField = field;
return true;
}
}
}
backingField = null;
return false;
}
}
@@ -0,0 +1,60 @@
using AsmResolver.DotNet;
using AsmResolver.DotNet.Signatures;
using System.Diagnostics.CodeAnalysis;
namespace AssetRipper.CIL;
public static class FieldDefinitionExtensions
{
public static bool IsInstance(this FieldDefinition field)
{
return !field.IsStatic;
}
private static bool IsPropertyBackingField(this FieldDefinition field, [NotNullWhen(true)] out string? propertyName)
{
string? name = field.Name;
if (name is ['<', ..] && name.EndsWith(">k__BackingField", StringComparison.Ordinal))
{
propertyName = name[1..^16];
return true;
}
else
{
propertyName = null;
return false;
}
}
public static bool IsPropertyBackingField(this FieldDefinition field, [NotNullWhen(true)] out PropertyDefinition? property)
{
if (field.IsPropertyBackingField(out string? propertyName))
{
property = field.DeclaringType?.Properties.FirstOrDefault(p => p.Name == propertyName);
return property is not null
&& field.IsStatic == property.IsStatic()
&& SignatureComparer.Default.Equals(field.Signature?.FieldType, property.Signature?.ReturnType);
}
else
{
property = null;
return false;
}
}
public static bool IsEventBackingField(this FieldDefinition field, [NotNullWhen(true)] out EventDefinition? @event)
{
if (field.IsPrivate)
{
@event = field.DeclaringType?.Events.FirstOrDefault(e => e.Name == field.Name);
return @event is not null
&& field.IsStatic == @event.IsStatic()
&& SignatureComparer.Default.Equals(@event.EventType?.ToTypeSignature(), field.Signature?.FieldType);
}
else
{
@event = null;
return false;
}
}
}
+68
View File
@@ -0,0 +1,68 @@
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.PE.DotNet.Cil;
namespace AssetRipper.CIL;
public static class MacroStandardization
{
/// <summary>
/// This method expands all macros in the collection and applies some standardizations, such as removing nop instructions.
/// </summary>
/// <param name="instructions">The collection to modify.</param>
public static void StandardizeMacros(this CilInstructionCollection instructions)
{
instructions.ExpandMacros();
instructions.RemoveNopInstructions();
}
private static void RemoveNopInstructions(this CilInstructionCollection instructions)
{
// Find labels that reference nop instructions.
HashSet<CilInstructionLabel> nopLabels = new();
foreach (CilInstruction instruction in instructions)
{
if (instruction.Operand is CilInstructionLabel { Instruction: not null } label && label.Instruction.OpCode == CilOpCodes.Nop)
{
nopLabels.Add(label);
}
else if (instruction.Operand is CilInstructionLabel[] labels) // switch
{
foreach (CilInstructionLabel l in labels)
{
if (l.Instruction is not null && l.Instruction.OpCode == CilOpCodes.Nop)
{
nopLabels.Add(l);
}
}
}
}
// Reassign labels to the next instruction, which is not a nop.
foreach (CilInstructionLabel label in nopLabels)
{
int index = instructions.IndexOf(label.Instruction!);
if (index < 0)
{
throw new InvalidOperationException("Label instruction not found");
}
for (int i = index + 1; i < instructions.Count; i++)
{
if (instructions[i].OpCode != CilOpCodes.Nop)
{
label.Instruction = instructions[i];
break;
}
}
}
// Remove nop instructions
for (int i = instructions.Count - 1; i >= 0; i--)
{
if (instructions[i].OpCode == CilOpCodes.Nop)
{
instructions.RemoveAt(i);
}
}
}
}
+23 -5
View File
@@ -23,9 +23,25 @@ public static class MethodDefinitionExtensions
MethodStubber.FillMethodBodyWithStub(methodDefinition);
}
public static bool IsInstance(this MethodDefinition methodDefinition)
{
return !methodDefinition.IsStatic;
}
public static bool IsInstanceConstructor(this MethodDefinition methodDefinition)
{
return methodDefinition.IsConstructor && !methodDefinition.IsStatic;
return methodDefinition.IsConstructor && methodDefinition.IsInstance();
}
public static bool IsStaticConstructor(this MethodDefinition methodDefinition)
{
return methodDefinition.IsConstructor && methodDefinition.IsStatic;
}
public static bool HasReturnType(this MethodDefinition methodDefinition)
{
return methodDefinition.Signature is not null
&& methodDefinition.Signature.ReturnType is not CorLibTypeSignature { ElementType: ElementType.Void };
}
internal static bool ShouldCallBaseConstructor(this MethodDefinition methodDefinition)
@@ -71,8 +87,9 @@ public static class MethodDefinitionExtensions
string backingFieldName = $"<{method.Name.Value[4..]}>k__BackingField";
FieldDefinition? field = method.DeclaringType.Fields.FirstOrDefault(f => f.Name == backingFieldName);
if (field is null
|| !SignatureComparer.Default.Equals(field.Signature?.FieldType, method.Signature?.ReturnType)
|| field.IsStatic != method.IsStatic)
|| !field.IsPrivate
|| field.IsStatic != method.IsStatic
|| !SignatureComparer.Default.Equals(field.Signature?.FieldType, method.Signature?.ReturnType))
{
backingField = null;
return false;
@@ -100,8 +117,9 @@ public static class MethodDefinitionExtensions
string backingFieldName = $"<{method.Name.Value[4..]}>k__BackingField";
FieldDefinition? field = method.DeclaringType.Fields.FirstOrDefault(f => f.Name == backingFieldName);
if (field is null
|| !SignatureComparer.Default.Equals(field.Signature?.FieldType, method.Parameters[0].ParameterType)
|| field.IsStatic != method.IsStatic)
|| !field.IsPrivate
|| field.IsStatic != method.IsStatic
|| !SignatureComparer.Default.Equals(field.Signature?.FieldType, method.Parameters[0].ParameterType))
{
backingField = null;
return false;
@@ -0,0 +1,45 @@
using AsmResolver.DotNet;
using AsmResolver.DotNet.Signatures;
using System.Diagnostics.CodeAnalysis;
namespace AssetRipper.CIL;
public static class PropertyDefinitionExtensions
{
public static bool HasBackingField(this PropertyDefinition property, [NotNullWhen(true)] out FieldDefinition? backingField)
{
string backingFieldName = $"<{property.Name}>k__BackingField";
backingField = property.DeclaringType?.Fields.FirstOrDefault(f => f.Name == backingFieldName);
if (backingField is null
|| !backingField.IsPrivate
|| backingField.IsStatic != property.IsStatic()
|| !SignatureComparer.Default.Equals(backingField.Signature?.FieldType, property.Signature?.ReturnType))
{
backingField = null;
return false;
}
else
{
return true;
}
}
public static bool HasGetMethod(this PropertyDefinition property)
{
return property.GetMethod is not null;
}
public static bool HasSetMethod(this PropertyDefinition property)
{
return property.SetMethod is not null;
}
public static bool HasBothAccessors(this PropertyDefinition property)
{
return property.HasGetMethod() && property.HasSetMethod();
}
public static bool IsInstance(this PropertyDefinition property) => property.Signature?.HasThis ?? false;
public static bool IsStatic(this PropertyDefinition property) => !property.Signature?.HasThis ?? false;
}
@@ -26,4 +26,9 @@ public static class TypeDefinitionExtensions
return result;
}
public static bool IsStaticClass(this TypeDefinition type)
{
return type.IsSealed && type.IsAbstract;
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
<PolySharpIncludeRuntimeSupportedAttributes>true</PolySharpIncludeRuntimeSupportedAttributes>
<Version>1.1.0</Version>
<Version>1.1.2</Version>
<AssemblyVersion>$(Version)</AssemblyVersion>
<Copyright>Copyright (c) 2024 ds5678</Copyright>
<Authors>ds5678</Authors>