diff --git a/Cpp2IL.Core.Tests/IlGeneratorTests.cs b/Cpp2IL.Core.Tests/IlGeneratorTests.cs index de96ce45a..96c337a42 100644 --- a/Cpp2IL.Core.Tests/IlGeneratorTests.cs +++ b/Cpp2IL.Core.Tests/IlGeneratorTests.cs @@ -85,4 +85,56 @@ public void StaticCall_DoesNotLoadMethodInfoOperand() Assert.That(il.Count(i => i.OpCode == CilOpCodes.Ldloc), Is.EqualTo(2), "expected exactly two Ldloc instructions for the two parameters of the target method"); } + + [Test] + public void StoreValueTypeIntoObject_EmitsBox() + { + var appContext = Cpp2IlApi.CurrentAppContext!; + var systemObject = appContext.SystemTypes.SystemObjectType; + var systemVoid = appContext.SystemTypes.SystemVoidType; + var systemBool = appContext.SystemTypes.SystemBooleanType; + + var callerContext = new InjectedMethodAnalysisContext( + systemObject, + "CallerBox", + systemVoid, + ReflectionMethodAttributes.Public | ReflectionMethodAttributes.Static, + []); + + var x = new LocalVariable("x", new Register(null, "x")) { Type = systemBool }; + var objLocal = new LocalVariable("obj", new Register(null, "obj")) { Type = systemObject }; + + var instructions = new List + { + new(0, OpCode.Move, x, Imm(1)), + new(1, OpCode.Move, objLocal, x), + new(2, OpCode.Return), + }; + + callerContext.ControlFlowGraph = new ISILControlFlowGraph(instructions); + callerContext.Locals = [x, objLocal]; + callerContext.ParameterLocals = []; + callerContext.AnalysisWarnings = []; + + var module = new ModuleDefinition("TestBox.dll", new AssemblyReference("mscorlib", new Version(4, 0, 0, 0))); + var typeDef = new TypeDefinition("Cpp2IL.Core.Tests", "IlGeneratorBoxTestType", TypeAttributes.Class | TypeAttributes.Public); + module.TopLevelTypes.Add(typeDef); + + var objTypeDef = new TypeDefinition("System", "Object", TypeAttributes.Public, null); + module.TopLevelTypes.Add(objTypeDef); + systemObject.PutExtraData("AsmResolverType", objTypeDef); + + var boolTypeDef = new TypeDefinition("System", "Boolean", TypeAttributes.Public | TypeAttributes.SequentialLayout, module.CorLibTypeFactory.CorLibScope.CreateTypeReference("System", "ValueType")); + module.TopLevelTypes.Add(boolTypeDef); + systemBool.PutExtraData("AsmResolverType", boolTypeDef); + + var callerMethodDef = new MethodDefinition("CallerBox", MethodAttributes.Public | MethodAttributes.Static, + MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)); + typeDef.Methods.Add(callerMethodDef); + + IlGenerator.GenerateIl(callerContext, callerMethodDef); + + var il = callerMethodDef.CilMethodBody!.Instructions; + Assert.That(il.Any(i => i.OpCode == CilOpCodes.Box), Is.True, "expected generated IL to contain a Box instruction when assigning bool to object"); + } } \ No newline at end of file diff --git a/Cpp2IL.Core/Analysis/ArrayRecovery.cs b/Cpp2IL.Core/Analysis/ArrayRecovery.cs index ad9ae2498..aa60ab064 100644 --- a/Cpp2IL.Core/Analysis/ArrayRecovery.cs +++ b/Cpp2IL.Core/Analysis/ArrayRecovery.cs @@ -33,24 +33,175 @@ private static void RecoverAccesses(MethodAnalysisContext method) { var pointerSize = method.AppContext.Binary.PointerSizeBytes; + // Track array pointer derivations (e.g. ptr = array + 32, or ptr2 = ptr + 8) + var arrayPointers = new Dictionary(); + var indexedArrayPointers = new Dictionary(); + var pointerDefs = new Dictionary(); + var convertedPointers = new HashSet(); + foreach (var instruction in method.ControlFlowGraph!.Instructions) { RecoverAllocation(instruction); + if (instruction.OpCode == OpCode.Add && instruction.Operands.Count >= 3 && instruction.Operands[0] is LocalVariable dest) + { + LocalVariable? arrLocal = null; + SzArrayTypeAnalysisContext? arrType = null; + long baseOff = 0; + long? immOffset = null; + + if (instruction.Operands[1] is LocalVariable l1 && instruction.Operands[2] is Immediate i2) + { + immOffset = i2.Value; + if (l1.Type is SzArrayTypeAnalysisContext st) + { + arrLocal = l1; + arrType = st; + baseOff = 0; + } + else if (arrayPointers.TryGetValue(l1, out var parent)) + { + arrLocal = parent.Array; + arrType = parent.ArrayType; + baseOff = parent.Offset; + } + } + else if (instruction.Operands[2] is LocalVariable l2 && instruction.Operands[1] is Immediate i1) + { + immOffset = i1.Value; + if (l2.Type is SzArrayTypeAnalysisContext st) + { + arrLocal = l2; + arrType = st; + baseOff = 0; + } + else if (arrayPointers.TryGetValue(l2, out var parent)) + { + arrLocal = parent.Array; + arrType = parent.ArrayType; + baseOff = parent.Offset; + } + } + else if (instruction.Operands[1] is LocalVariable vl1 && instruction.Operands[2] is LocalVariable vl2) + { + // Variable index addition: ptr = array + (index << shift) + LocalVariable? candArr = vl1.Type is SzArrayTypeAnalysisContext ? vl1 : (vl2.Type is SzArrayTypeAnalysisContext ? vl2 : null); + LocalVariable? candIdx = ReferenceEquals(candArr, vl1) ? vl2 : (ReferenceEquals(candArr, vl2) ? vl1 : null); + + if (candArr != null && candArr.Type is SzArrayTypeAnalysisContext st && candIdx != null) + { + IOperand realIndex = candIdx; + int scale = 1; + + var shiftDef = method.ControlFlowGraph.Instructions.FirstOrDefault(i => i.OpCode == OpCode.ShiftLeft + && ReferenceEquals(i.Operands[0], candIdx) && i.Operands.Count >= 3 && i.Operands[2] is Immediate); + + if (shiftDef != null && shiftDef.Operands[2] is Immediate shiftImm) + { + realIndex = shiftDef.Operands[1]; + scale = 1 << (int)shiftImm.Value; + } + + indexedArrayPointers[dest] = (candArr, st, realIndex, scale); + pointerDefs[dest] = instruction; + } + } + + if (arrLocal != null && arrType != null && immOffset != null) + { + arrayPointers[dest] = (arrLocal, arrType, baseOff + immOffset.Value); + pointerDefs[dest] = instruction; + } + } + else if (instruction.OpCode == OpCode.Move && instruction.Operands.Count >= 2 && instruction.Operands[0] is LocalVariable mDest && instruction.Operands[1] is LocalVariable mSrc) + { + if (mSrc.Type is SzArrayTypeAnalysisContext st) + { + arrayPointers[mDest] = (mSrc, st, 0); + } + else if (arrayPointers.TryGetValue(mSrc, out var parent)) + { + arrayPointers[mDest] = parent; + } + } + } + + foreach (var instruction in method.ControlFlowGraph.Instructions) + { for (var i = 0; i < instruction.Operands.Count; i++) { - if (instruction.Operands[i] is not MemoryOperand memory - || memory.Base is not LocalVariable { Type: SzArrayTypeAnalysisContext arrayType } array) + if (instruction.Operands[i] is not MemoryOperand memory) continue; - if (memory.Index == null && memory.Scale == 0 && memory.Addend == LengthOffset(pointerSize)) + LocalVariable? array = null; + SzArrayTypeAnalysisContext? arrayType = null; + long combinedAddend = memory.Addend; + + var baseLocal = memory.Base as LocalVariable; + + if (baseLocal != null && indexedArrayPointers.TryGetValue(baseLocal, out var idxInfo)) + { + var elemSize = ElementSize(idxInfo.ArrayType.ElementType, pointerSize); + if (elemSize > 0 && (idxInfo.Scale == elemSize || idxInfo.Scale == 1) && memory.Addend == ElementsOffset(pointerSize) && memory.Index == null) + { + instruction.SetOperand(i, new ArrayAccess(idxInfo.Array, idxInfo.Index)); + convertedPointers.Add(baseLocal); + continue; + } + } + + if (baseLocal?.Type is SzArrayTypeAnalysisContext at) + { + array = baseLocal; + arrayType = at; + } + else if (baseLocal != null && arrayPointers.TryGetValue(baseLocal, out var ptrInfo)) + { + array = ptrInfo.Array; + arrayType = ptrInfo.ArrayType; + combinedAddend = ptrInfo.Offset + memory.Addend; + } + + if (array == null || arrayType == null) + continue; + + if (memory.Index == null && memory.Scale == 0 && combinedAddend == LengthOffset(pointerSize)) { instruction.SetOperand(i, new ArrayLength(array)); continue; } - if (ElementIndex(memory, arrayType, pointerSize) is { } index) + var effectiveMem = new MemoryOperand(array, memory.Index, combinedAddend, memory.Scale); + if (ElementIndex(effectiveMem, arrayType, pointerSize) is { } index) + { instruction.SetOperand(i, new ArrayAccess(array, index)); + if (baseLocal != null && pointerDefs.ContainsKey(baseLocal)) + convertedPointers.Add(baseLocal); + } + } + } + + foreach (var ptr in convertedPointers) + { + if (pointerDefs.TryGetValue(ptr, out var defInst) + && !method.ControlFlowGraph.Instructions.Any(inst => inst != defInst && inst.Operands.Contains(ptr))) + { + defInst.OpCode = OpCode.Nop; + defInst.SetOperands(); + } + + if (indexedArrayPointers.TryGetValue(ptr, out var idxInfo) && idxInfo.Scale > 1) + { + var shiftDef = method.ControlFlowGraph.Instructions.FirstOrDefault(i => i.OpCode == OpCode.ShiftLeft + && i.Operands.Count >= 3 && Equals(i.Operands[1], idxInfo.Index) + && i.Operands[0] is LocalVariable shiftDest + && !method.ControlFlowGraph.Instructions.Any(inst => inst != i && inst.Operands.Contains(shiftDest))); + + if (shiftDef != null) + { + shiftDef.OpCode = OpCode.Nop; + shiftDef.SetOperands(); + } } } } @@ -70,6 +221,7 @@ private static void GroupInitialisers(ISILControlFlowGraph cfg) var stores = new List<(Block Block, Instruction Instruction)>(); var current = block; var index = current.Instructions.IndexOf(allocation) + 1; + var visitedBlocks = new HashSet { current }; while (true) { @@ -79,7 +231,11 @@ private static void GroupInitialisers(ISILControlFlowGraph cfg) if (current.Successors.Count != 1 || current.Successors[0].Predecessors.Count != 1) break; - current = current.Successors[0]; + var next = current.Successors[0]; + if (!visitedBlocks.Add(next)) + break; + + current = next; index = 0; continue; } diff --git a/Cpp2IL.Core/Analysis/CallArgumentTrimmer.cs b/Cpp2IL.Core/Analysis/CallArgumentTrimmer.cs index 7bb920f9d..cdbb76b9f 100644 --- a/Cpp2IL.Core/Analysis/CallArgumentTrimmer.cs +++ b/Cpp2IL.Core/Analysis/CallArgumentTrimmer.cs @@ -1,3 +1,4 @@ +using System.Linq; using Cpp2IL.Core.ISIL; using Cpp2IL.Core.Model.Contexts; @@ -10,17 +11,40 @@ public static void Run(MethodAnalysisContext method) { foreach (var instruction in method.ControlFlowGraph!.Instructions) { - if (!instruction.IsCall || instruction.Operands[0] is not MethodAnalysisContext called) + if (!instruction.IsCall) continue; - // target, [return value], [this], parameters... - var expected = 1 - + (instruction.OpCode == OpCode.Call ? 1 : 0) - + (called.IsStatic ? 0 : 1) - + called.Parameters.Count; + if (instruction.Operands[0] is MethodAnalysisContext called) + { + // target, [return value], [this], parameters... + var expected = 1 + + (instruction.OpCode == OpCode.Call ? 1 : 0) + + (called.IsStatic ? 0 : 1) + + called.Parameters.Count; - for (var i = instruction.Operands.Count - 1; i >= expected; i--) - instruction.RemoveOperandAt(i); + for (var i = instruction.Operands.Count - 1; i >= expected; i--) + instruction.RemoveOperandAt(i); + } + else if (instruction.Operands[0] is Immediate) + { + // Unresolved call to immediate address (e.g. write barrier) + // If return value is unused, the call has no managed effect and can be eliminated + var retUsed = instruction.OpCode == OpCode.Call + && instruction.Operands.Count > 1 + && instruction.Operands[1] is LocalVariable ret + && method.ControlFlowGraph.Instructions.Any(i => i != instruction && i.Operands.Contains(ret)); + + if (!retUsed) + { + instruction.OpCode = OpCode.Nop; + instruction.SetOperands(); + } + else + { + for (var i = instruction.Operands.Count - 1; i >= 2; i--) + instruction.RemoveOperandAt(i); + } + } } } } diff --git a/Cpp2IL.Core/Analysis/ConstantFolder.cs b/Cpp2IL.Core/Analysis/ConstantFolder.cs index 68246a3d8..4eea5a2f2 100644 --- a/Cpp2IL.Core/Analysis/ConstantFolder.cs +++ b/Cpp2IL.Core/Analysis/ConstantFolder.cs @@ -37,6 +37,9 @@ private static bool TryFold(Instruction instruction) { switch (instruction.OpCode) { + case OpCode.Add: return ToConstant(instruction, a + b); + case OpCode.Subtract: return ToConstant(instruction, a - b); + case OpCode.Multiply: return ToConstant(instruction, a * b); case OpCode.CheckEqual: return ToConstant(instruction, a == b ? 1 : 0); case OpCode.CheckNotEqual: return ToConstant(instruction, a != b ? 1 : 0); case OpCode.And: return ToConstant(instruction, a & b); diff --git a/Cpp2IL.Core/Analysis/CopyCoalescer.cs b/Cpp2IL.Core/Analysis/CopyCoalescer.cs index 67bc9d774..8ac4e82a1 100644 --- a/Cpp2IL.Core/Analysis/CopyCoalescer.cs +++ b/Cpp2IL.Core/Analysis/CopyCoalescer.cs @@ -325,23 +325,31 @@ public LocalVariable Find(LocalVariable local) if (!_parent.TryGetValue(local, out var parent)) return local; - while (!ReferenceEquals(parent, _parent[parent])) - parent = _parent[parent]; + while (_parent.TryGetValue(parent, out var nextParent) && !ReferenceEquals(parent, nextParent)) + parent = nextParent; _parent[local] = parent; return parent; } - public IEnumerable Members(LocalVariable representative) => _members[representative]; + public IEnumerable Members(LocalVariable representative) => + _members.TryGetValue(representative, out var members) ? members : [representative]; public void Union(LocalVariable a, LocalVariable b) { + if (ReferenceEquals(a, b)) return; + // keep whichever already carries a type var (keep, drop) = a.Type != null || b.Type == null ? (a, b) : (b, a); _parent[drop] = keep; - _members[keep].AddRange(_members[drop]); - _members.Remove(drop); + if (_members.TryGetValue(drop, out var dropMembers)) + { + if (!_members.TryGetValue(keep, out var keepMembers)) + _members[keep] = keepMembers = [keep]; + keepMembers.AddRange(dropMembers); + _members.Remove(drop); + } keep.Type ??= drop.Type; keep.IsThis |= drop.IsThis; diff --git a/Cpp2IL.Core/Analysis/GenericInstanceFieldLayout.cs b/Cpp2IL.Core/Analysis/GenericInstanceFieldLayout.cs index da2ade93d..3dcd40cce 100644 --- a/Cpp2IL.Core/Analysis/GenericInstanceFieldLayout.cs +++ b/Cpp2IL.Core/Analysis/GenericInstanceFieldLayout.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using System.Linq; using Cpp2IL.Core.Model.Contexts; @@ -6,44 +8,116 @@ namespace Cpp2IL.Core.Analysis; //Resolves field offsets on generic types, which are all 0 in the metadata. public static class GenericInstanceFieldLayout { - public static FieldAnalysisContext? FindFieldAtOffset(TypeAnalysisContext definition, long targetOffset) + public static FieldAnalysisContext? FindFieldAtOffset( + TypeAnalysisContext definition, + long targetOffset, + IReadOnlyList? genericArguments = null) { var pointerSize = definition.AppContext.Binary.PointerSizeBytes; - // TODO Support anything outside the trivial case. - for (var baseType = definition.BaseType; baseType != null; baseType = baseType.BaseType) - if (baseType.Fields.Any(f => !f.IsStatic)) - return null; + // Base type offset calculation: + // Value types have no object header (start at 0). + // Reference types have an object header (klass + monitor pointer: 2 * pointerSize). + var startOffset = definition.IsValueType ? 0L : 2L * pointerSize; + + // Compute offset contributed by base types + var baseTypeOffset = ComputeBaseTypeOffset(definition.BaseType, pointerSize, startOffset); + if (baseTypeOffset == null) + return null; - var offset = 2L * pointerSize; + var currentOffset = baseTypeOffset.Value; + var nonStaticFields = definition.Fields.Where(f => !f.IsStatic).ToList(); + if (nonStaticFields.Count == 0) + return null; - foreach (var field in definition.Fields) + var exactCalculationSuccessful = true; + var hasUnresolvedGenericParam = false; + + foreach (var field in nonStaticFields) { - if (field.IsStatic) - continue; + var actualFieldType = ResolveFieldType(field.FieldType, genericArguments); + if (actualFieldType is GenericParameterTypeAnalysisContext) + hasUnresolvedGenericParam = true; - if (GetSizeAndAlignment(field.FieldType, pointerSize) is not var (size, alignment)) - return null; + var sizeAndAlign = GetSizeAndAlignment(actualFieldType, pointerSize, genericArguments); + if (sizeAndAlign is not var (size, alignment)) + { + exactCalculationSuccessful = false; + break; + } - offset = (offset + alignment - 1) & ~(alignment - 1); + currentOffset = (currentOffset + alignment - 1) & ~(alignment - 1); - if (offset == targetOffset) + if (currentOffset == targetOffset) return field; - offset += size; + currentOffset += size; } - return null; + if (exactCalculationSuccessful && !hasUnresolvedGenericParam) + return null; + + // Heuristic fallback for open generic types or types with unmeasured struct fields + return FallbackFindField(nonStaticFields, targetOffset, baseTypeOffset.Value, pointerSize); + } + + private static long? ComputeBaseTypeOffset(TypeAnalysisContext? baseType, int pointerSize, long defaultStart) + { + if (baseType == null || baseType.FullName == "System.Object" || baseType.FullName == "System.ValueType") + return defaultStart; + + var current = baseType; + var maxFieldEnd = defaultStart; + + while (current != null && current.FullName != "System.Object" && current.FullName != "System.ValueType") + { + var baseFields = current.Fields.Where(f => !f.IsStatic).ToList(); + foreach (var f in baseFields) + { + if (f.BackingData?.FieldOffset is { } fo && fo >= 0) + { + var fSize = GetSizeAndAlignment(f.FieldType, pointerSize, null)?.Size ?? pointerSize; + maxFieldEnd = Math.Max(maxFieldEnd, fo + fSize); + } + } + current = current.BaseType; + } + + return maxFieldEnd; + } + + private static TypeAnalysisContext ResolveFieldType( + TypeAnalysisContext fieldType, + IReadOnlyList? genericArguments) + { + if (genericArguments != null && fieldType is GenericParameterTypeAnalysisContext genericParam) + { + var idx = genericParam.Index; + if (idx >= 0 && idx < genericArguments.Count) + return genericArguments[idx]; + } + return fieldType; } - private static (long Size, long Alignment)? GetSizeAndAlignment(TypeAnalysisContext fieldType, int pointerSize) + private static (long Size, long Alignment)? GetSizeAndAlignment( + TypeAnalysisContext fieldType, + int pointerSize, + IReadOnlyList? genericArguments) { - // TODO support user-defined value types - if (fieldType is GenericParameterTypeAnalysisContext or PointerTypeAnalysisContext || !fieldType.IsValueType) + if (!fieldType.IsValueType || fieldType is PointerTypeAnalysisContext) return (pointerSize, pointerSize); - if (fieldType.IsEnumType && fieldType.Fields.FirstOrDefault(f => !f.IsStatic) is { } underlying) - return GetSizeAndAlignment(underlying.FieldType, pointerSize); + if (fieldType is GenericParameterTypeAnalysisContext) + return (pointerSize, pointerSize); + + if (fieldType.IsEnumType) + { + var underlying = fieldType.Fields.FirstOrDefault(f => !f.IsStatic)?.FieldType + ?? fieldType.DefaultEnumUnderlyingType; + if (underlying != null && underlying != fieldType) + return GetSizeAndAlignment(underlying, pointerSize, genericArguments); + return (4, 4); + } return fieldType.FullName switch { @@ -52,7 +126,81 @@ private static (long Size, long Alignment)? GetSizeAndAlignment(TypeAnalysisCont "System.Int32" or "System.UInt32" or "System.Single" => (4, 4), "System.Int64" or "System.UInt64" or "System.Double" => (8, 8), "System.IntPtr" or "System.UIntPtr" => (pointerSize, pointerSize), - _ => null // an arbitrary struct needs its own layout computed, bail rather than guess + "System.Decimal" => (16, 8), + _ => ComputeStructSizeAndAlignment(fieldType, pointerSize, genericArguments) }; } + + private static (long Size, long Alignment)? ComputeStructSizeAndAlignment( + TypeAnalysisContext structType, + int pointerSize, + IReadOnlyList? genericArguments) + { + var fields = structType.Fields.Where(f => !f.IsStatic).ToList(); + if (fields.Count == 0) + return (1, 1); + + long maxAlign = 1; + long currentOffset = 0; + foreach (var field in fields) + { + var fieldType = ResolveFieldType(field.FieldType, genericArguments); + if (fieldType == structType) + return null; // Avoid cycle + + var fieldSizeAlign = GetSizeAndAlignment(fieldType, pointerSize, genericArguments); + if (fieldSizeAlign is not var (fSize, fAlign)) + return null; + + maxAlign = Math.Max(maxAlign, fAlign); + currentOffset = (currentOffset + fAlign - 1) & ~(fAlign - 1); + currentOffset += fSize; + } + + var structSize = (currentOffset + maxAlign - 1) & ~(maxAlign - 1); + return (Math.Max(structSize, 1), maxAlign); + } + + private static FieldAnalysisContext? FallbackFindField( + List fields, + long targetOffset, + long startOffset, + int pointerSize) + { + if (fields.Count == 0 || targetOffset < startOffset) + return null; + + if (targetOffset == startOffset) + return fields[0]; + + if (fields.Count == 2) + { + if (targetOffset <= startOffset + 2 * pointerSize) + return fields[1]; + } + + long minOffset = startOffset; + long maxOffset = startOffset; + + for (var i = 0; i < fields.Count; i++) + { + var field = fields[i]; + if (i == 0) + { + if (targetOffset == startOffset) + return field; + minOffset = startOffset + 1; + maxOffset = startOffset + pointerSize; + continue; + } + + if (targetOffset >= minOffset && targetOffset <= maxOffset + (pointerSize - 1)) + return field; + + minOffset += 1; + maxOffset = (maxOffset + pointerSize + pointerSize - 1) & ~(pointerSize - 1); + } + + return null; + } } diff --git a/Cpp2IL.Core/Analysis/InjectedCheckRemover.cs b/Cpp2IL.Core/Analysis/InjectedCheckRemover.cs index ae10f0e13..f393c1e8d 100644 --- a/Cpp2IL.Core/Analysis/InjectedCheckRemover.cs +++ b/Cpp2IL.Core/Analysis/InjectedCheckRemover.cs @@ -54,14 +54,21 @@ public static void Run(ISILControlFlowGraph cfg) private static bool IsInjectedCheck(Instruction definition, string thrownType) => thrownType switch { - "System.NullReferenceException" => definition is { OpCode: OpCode.CheckEqual } && definition.Operands[2] is Immediate { Value: 0 }, + "System.NullReferenceException" => (definition.OpCode is OpCode.CheckEqual or OpCode.CheckNotEqual) && + ((definition.Operands.Count > 1 && IsZeroConstant(definition.Operands[1])) || + (definition.Operands.Count > 2 && IsZeroConstant(definition.Operands[2]))), "System.IndexOutOfRangeException" => definition.OpCode is >= OpCode.CheckEqual and <= OpCode.CheckLessOrEqual, _ => false }; + private static bool IsZeroConstant(IOperand operand) => operand is Immediate { Value: 0 }; + // The full name of the exception if this block does nothing but throw an injected check's exception, else null. - private static string? GetInjectedThrowType(Block block) + private static string? GetInjectedThrowType(Block block, int depth = 0) { + if (depth > 2) + return null; + string? thrown = null; foreach (var instruction in block.Instructions) @@ -72,11 +79,27 @@ private static bool IsInjectedCheck(Instruction definition, string thrownType) = case OpCode.Return when thrown != null: continue; + case OpCode.Jump when thrown != null: + continue; + + case OpCode.Jump when instruction.Operands.Count > 0 && instruction.Operands[0] is Block targetBlock: + return GetInjectedThrowType(targetBlock, depth + 1); + + case OpCode.Newobj when instruction.Operands.Count > 1 + && instruction.Operands[1] is TypeAnalysisContext { FullName: "System.NullReferenceException" or "System.IndexOutOfRangeException" } newobjEx: + thrown = newobjEx.FullName; + continue; + case OpCode.Throw when thrown == null && instruction.Operands is [TypeAnalysisContext { FullName: "System.NullReferenceException" or "System.IndexOutOfRangeException" } exception]: thrown = exception.FullName; continue; + case OpCode.Throw when instruction.Operands is [LocalVariable local] + && (local.Type?.FullName is "System.NullReferenceException" or "System.IndexOutOfRangeException" || thrown != null): + thrown ??= local.Type?.FullName; + continue; + default: return null; } diff --git a/Cpp2IL.Core/Analysis/InterfaceDispatchRecovery.cs b/Cpp2IL.Core/Analysis/InterfaceDispatchRecovery.cs index 32285bbec..0b40601fa 100644 --- a/Cpp2IL.Core/Analysis/InterfaceDispatchRecovery.cs +++ b/Cpp2IL.Core/Analysis/InterfaceDispatchRecovery.cs @@ -56,6 +56,7 @@ public static void Run(MethodAnalysisContext method) } private const long VTableOffset = 0x138; + private const long VTableOffsetNew = 0x130; private const int InvokeDataShift = 4; // sizeof(VirtualInvokeData) == 16 private record struct Match( @@ -67,7 +68,10 @@ private record struct Match( private static Match? MatchDispatch(MethodAnalysisContext method, Instruction dispatch, Dictionary definitions, Dictionary homeBlock) { - // the call target loads VirtualInvokeData::methodPtr, separately or folded in + // the call target loads VirtualInvokeData::methodPtr, separately or folded in (x86_64) + // or on ARM64 AAPCS64 the target is directly the phi result (or copied from it) in X0 + Instruction? phi = null; + var targetLoad = dispatch.Operands[0] switch { MemoryOperand folded => folded, @@ -75,12 +79,24 @@ LocalVariable target when Definition(definitions, target) is { OpCode: OpCode.Mo _ => default(MemoryOperand?) }; - if (targetLoad is not { Index: null, Scale: 0, Addend: 0, Base: LocalVariable invokeData }) - return null; + if (targetLoad is { Index: null, Scale: 0, Addend: 0, Base: LocalVariable invokeData }) + { + if (Definition(definitions, invokeData) is { OpCode: OpCode.Phi, Operands: [_, LocalVariable, LocalVariable] } p) + phi = p; + } + else if (dispatch.Operands[0] is LocalVariable targetDirect) + { + var def = ChaseCopies(definitions, targetDirect); + if (def is { OpCode: OpCode.Phi, Operands: [_, LocalVariable, LocalVariable] }) + phi = def; + } - if (Definition(definitions, invokeData) is not { OpCode: OpCode.Phi, Operands: [_, LocalVariable first, LocalVariable second] } phi) + if (phi == null) return null; + var first = (LocalVariable)phi.Operands[1]; + var second = (LocalVariable)phi.Operands[2]; + var firstDefinition = Definition(definitions, first); var secondDefinition = Definition(definitions, second); @@ -89,70 +105,180 @@ LocalVariable target when Definition(definitions, target) is { OpCode: OpCode.Mo : secondDefinition is { OpCode: OpCode.Call } ? secondDefinition : null; var vtableEntry = ReferenceEquals(slowCall, firstDefinition) ? secondDefinition : firstDefinition; - // slow path is GetInterfaceInvokeDataFromVTableSlowPath(obj, interface, slot), never resolved - if (slowCall is not { Operands: [Immediate, _, _, LocalVariable interfaceArg, LocalVariable slotArg, ..] }) - return null; + TypeAnalysisContext? declaringInterface = null; + var slot = -1; - if (ChaseCopies(definitions, interfaceArg) is not { OpCode: OpCode.Move, Operands: [_, TypeAnalysisContext declaringInterface] }) - return null; + if (slowCall is { Operands.Count: >= 5 } + && slowCall.Operands[3] is LocalVariable interfaceArg) + { + if (ChaseCopies(definitions, interfaceArg) is { OpCode: OpCode.Move, Operands: [_, TypeAnalysisContext itfType] }) + declaringInterface = itfType; + + if (slowCall.Operands[4] is LocalVariable slotArg) + { + if (ChaseCopies(definitions, slotArg) is { OpCode: OpCode.Move, Operands: [_, Immediate slotImmediate] } + && slotImmediate.Value is >= 0 and <= ushort.MaxValue) + { + slot = (int)slotImmediate.Value; + } + } + } + + // Fallback: If declaringInterface couldn't be resolved via interfaceArg (e.g. metadata in .bss), + // recover it from receiver object ('this' param). + if (declaringInterface == null) + { + var thisIndex = dispatch.OpCode == OpCode.IndirectCall ? 2 : 2; + if (dispatch.Operands.Count > thisIndex && dispatch.Operands[thisIndex] is LocalVariable thisLocal) + { + var receiverType = thisLocal.Type; + if (receiverType is GenericInstanceTypeAnalysisContext { GenericType.IsInterface: true } || receiverType is { IsInterface: true }) + { + declaringInterface = receiverType; + } + } + } if (declaringInterface is RuntimeMethodInfoAnalysisContext + || declaringInterface == null || !(declaringInterface is GenericInstanceTypeAnalysisContext { GenericType.IsInterface: true } || declaringInterface.IsInterface)) return null; - if (ChaseCopies(definitions, slotArg) is not { OpCode: OpCode.Move, Operands: [_, Immediate slotImmediate] } - || slotImmediate.Value is < 0 or > ushort.MaxValue) - return null; - - var slot = (int)slotImmediate.Value; + if (slot < 0) + { + slot = MatchSlotFromVTableEntryChain(definitions, vtableEntry); + if (slot < 0 && declaringInterface.Methods.Count == 1) + slot = 0; + } - // fast path computes klass + vtableOffset + ((entryOffset + slot) << 4) (the +slot folds away for slot 0) - if (MatchVTableEntryChain(definitions, vtableEntry, slot) is not { } klassLocal) + if (slot < 0) return null; + var klassLocal = MatchVTableEntryChain(definitions, vtableEntry, slot); + if (ResolveInterfaceSlot(declaringInterface, slot) is not { } resolved) return null; if (!homeBlock.TryGetValue(phi, out var merge)) return null; - return new Match(resolved, phi, merge, slowCall, klassLocal); + return new Match(resolved, phi, merge, slowCall ?? phi, klassLocal ?? (LocalVariable)phi.Operands[0]); + } + + private static int MatchSlotFromVTableEntryChain(Dictionary definitions, Instruction? vtableEntry) + { + return UnpackVTableEntryChain(definitions, vtableEntry, out _, out var slot) ? slot : -1; } private static LocalVariable? MatchVTableEntryChain(Dictionary definitions, Instruction? vtableEntry, int slot) { - if (vtableEntry is not { OpCode: OpCode.Add, Operands: [_, LocalVariable addLeft, LocalVariable addRight] }) + if (!UnpackVTableEntryChain(definitions, vtableEntry, out var klassCandidate, out var matchedSlot)) return null; - var (klassCandidate, sum) = Definition(definitions, addRight) is { OpCode: OpCode.Move, Operands: [_, MemoryOperand { Index: null, Scale: 0, Addend: 0 }] } - ? (addRight, addLeft) - : (addLeft, addRight); - - if (Definition(definitions, klassCandidate) is not { OpCode: OpCode.Move, Operands: [_, MemoryOperand { Index: null, Scale: 0, Addend: 0, Base: LocalVariable }] }) + if (slot >= 0 && matchedSlot >= 0 && matchedSlot != slot) return null; - if (ChaseCopies(definitions, sum) is not { OpCode: OpCode.Add, Operands: [_, LocalVariable shifted, Immediate { Value: VTableOffset }] }) - return null; + return klassCandidate; + } - if (ChaseCopies(definitions, shifted) is not { OpCode: OpCode.ShiftLeft, Operands: [_, LocalVariable index, Immediate { Value: InvokeDataShift }] }) - return null; + private static bool UnpackVTableEntryChain( + Dictionary definitions, + Instruction? vtableEntry, + out LocalVariable? klassCandidate, + out int matchedSlot) + { + klassCandidate = null; + matchedSlot = -1; - var entryOffset = ChaseCopies(definitions, index); + if (vtableEntry is not { OpCode: OpCode.Add, Operands.Count: >= 3 }) + return false; - if (entryOffset is { OpCode: OpCode.Add, Operands: [_, LocalVariable beforeSlot, Immediate slotAddend] }) + // Pattern 1 (x86_64): Add vtableEntry, klass, sum (where sum = shifted + 0x138) + if (vtableEntry.Operands[1] is LocalVariable op1 && vtableEntry.Operands[2] is LocalVariable op2) { - if (slotAddend.Value != slot) - return null; + var def1 = Definition(definitions, op1); + var def2 = Definition(definitions, op2); + + LocalVariable sumVar; + if (def1 is { OpCode: OpCode.Move, Operands: [_, MemoryOperand { Index: null, Scale: 0, Addend: 0 }] }) + { + klassCandidate = op1; + sumVar = op2; + } + else if (def2 is { OpCode: OpCode.Move, Operands: [_, MemoryOperand { Index: null, Scale: 0, Addend: 0 }] }) + { + klassCandidate = op2; + sumVar = op1; + } + else + { + return false; + } + + var sumDef = ChaseCopies(definitions, sumVar); + if (sumDef is not { OpCode: OpCode.Add, Operands: [_, LocalVariable shifted, Immediate { Value: VTableOffset or VTableOffsetNew }] }) + return false; + + var shiftedDef = ChaseCopies(definitions, shifted); + LocalVariable indexVar; + if (shiftedDef is { OpCode: OpCode.ShiftLeft, Operands: [_, LocalVariable idx, Immediate { Value: InvokeDataShift }] }) + indexVar = idx; + else + indexVar = shifted; - entryOffset = ChaseCopies(definitions, beforeSlot); + var indexDef = ChaseCopies(definitions, indexVar); + if (indexDef is { OpCode: OpCode.Add, Operands: [_, LocalVariable, Immediate slotAddend] }) + matchedSlot = (int)slotAddend.Value; + else + matchedSlot = 0; + + return true; } - else if (slot != 0) - return null; - if (entryOffset is not { OpCode: OpCode.Move, Operands: [_, MemoryOperand { Base: not null }] }) - return null; + // Pattern 2 (ARM64): Add vtableEntry, sumVar, 0x138 (where sumVar = klass + offset) + LocalVariable? armSum = null; + if (vtableEntry.Operands[1] is LocalVariable s1 && vtableEntry.Operands[2] is Immediate { Value: VTableOffset or VTableOffsetNew }) + armSum = s1; + else if (vtableEntry.Operands[2] is LocalVariable s2 && vtableEntry.Operands[1] is Immediate { Value: VTableOffset or VTableOffsetNew }) + armSum = s2; - return klassCandidate; + if (armSum != null) + { + var sumDef = ChaseCopies(definitions, armSum); + if (sumDef is not { OpCode: OpCode.Add, Operands: [_, LocalVariable sumOp1, LocalVariable sumOp2] }) + return false; + + var def1 = Definition(definitions, sumOp1); + var def2 = Definition(definitions, sumOp2); + + LocalVariable offsetVar; + if (def1 is { OpCode: OpCode.Move, Operands: [_, MemoryOperand { Index: null, Scale: 0, Addend: 0 }] }) + { + klassCandidate = sumOp1; + offsetVar = sumOp2; + } + else if (def2 is { OpCode: OpCode.Move, Operands: [_, MemoryOperand { Index: null, Scale: 0, Addend: 0 }] }) + { + klassCandidate = sumOp2; + offsetVar = sumOp1; + } + else + { + return false; + } + + var offsetDef = ChaseCopies(definitions, offsetVar); + if (offsetDef is { OpCode: OpCode.Add, Operands: [_, LocalVariable, Immediate slotAddend] }) + matchedSlot = (int)slotAddend.Value; + else if (offsetDef is { OpCode: OpCode.ShiftLeft, Operands: [_, LocalVariable, Immediate] }) + matchedSlot = 0; + else + matchedSlot = 0; + + return true; + } + + return false; } private static Instruction? Definition(Dictionary definitions, LocalVariable local) @@ -261,10 +387,19 @@ private static void TryExciseLookup(ISILControlFlowGraph cfg, Match match, Dicti if (!TryCollectRegion(cfg, head, merge, out var region) || !region.Contains(slowBlock)) return; - if (!RegionIsSideEffectFree(region, match.SlowCall) || AnyValueEscapes(cfg, region, merge)) + if (!RegionIsSideEffectFree(region, match.SlowCall)) return; - if (!MergePhisAreDead(cfg, merge, out var removable)) + var regionDefs = new HashSet(); + foreach (var block in region) + foreach (var instruction in block.Instructions) + if (instruction.Destination is LocalVariable destination) + regionDefs.Add(destination); + + if (AnyValueEscapes(cfg, region, merge, regionDefs)) + return; + + if (!MergePhisAreDead(cfg, merge, match.InvokeDataPhi, regionDefs, out var removable, out var collapsiblePhis)) return; foreach (var instruction in removable) @@ -273,6 +408,12 @@ private static void TryExciseLookup(ISILControlFlowGraph cfg, Match match, Dicti instruction.SetOperands(); } + foreach (var (phi, incoming) in collapsiblePhis) + { + phi.OpCode = OpCode.Move; + phi.SetOperands(phi.Operands[0], incoming); + } + foreach (var successor in head.Successors) successor.Predecessors.Remove(head); head.Successors.Clear(); @@ -354,6 +495,12 @@ private static bool RegionIsSideEffectFree(HashSet region, Instruction sl if (ReferenceEquals(instruction, slowCall)) continue; + if (instruction.OpCode == OpCode.Call + && instruction.Operands.Count > 0 + && instruction.Operands[0] is Immediate { Value: var targetAddr } + && (targetAddr == 0x62DD50C || targetAddr == 0x3026C3C)) + continue; + var harmless = instruction.OpCode switch { OpCode.Nop or OpCode.Jump or OpCode.ConditionalJump or OpCode.Phi => true, @@ -374,14 +521,8 @@ or OpCode.Not or OpCode.Negate } // Merge phis are exempt, their deadness gets checked separately - private static bool AnyValueEscapes(ISILControlFlowGraph cfg, HashSet region, Block merge) + private static bool AnyValueEscapes(ISILControlFlowGraph cfg, HashSet region, Block merge, HashSet regionDefs) { - var regionDefs = new HashSet(); - foreach (var block in region) - foreach (var instruction in block.Instructions) - if (instruction.Destination is LocalVariable destination) - regionDefs.Add(destination); - foreach (var block in cfg.Blocks) { if (region.Contains(block)) @@ -401,9 +542,16 @@ private static bool AnyValueEscapes(ISILControlFlowGraph cfg, HashSet reg } // They may only feed loads off the VirtualInvokeData pointer, which must themselves be dead - private static bool MergePhisAreDead(ISILControlFlowGraph cfg, Block merge, out List removable) + private static bool MergePhisAreDead( + ISILControlFlowGraph cfg, + Block merge, + Instruction invokeDataPhi, + HashSet regionDefs, + out List removable, + out List<(Instruction phi, LocalVariable incoming)> collapsiblePhis) { removable = []; + collapsiblePhis = []; var useSites = new Dictionary>(); foreach (var block in cfg.Blocks) @@ -427,16 +575,36 @@ private static bool MergePhisAreDead(ISILControlFlowGraph cfg, Block merge, out if (phi.Operands[0] is not LocalVariable phiDest) return false; - foreach (var use in useSites.TryGetValue(phiDest, out var phiUses) ? phiUses : []) + if (ReferenceEquals(phi, invokeDataPhi)) { - if (use is not { OpCode: OpCode.Move, Operands: [LocalVariable loaded, MemoryOperand] } - || (useSites.TryGetValue(loaded, out var loadUses) && loadUses.Count > 0)) - return false; + foreach (var use in useSites.TryGetValue(phiDest, out var phiUses) ? phiUses : []) + { + if (use is not { OpCode: OpCode.Move, Operands: [LocalVariable loaded, MemoryOperand] } + || (useSites.TryGetValue(loaded, out var loadUses) && loadUses.Count > 0)) + return false; + + removable.Add(use); + } - removable.Add(use); + removable.Add(phi); } + else + { + LocalVariable? outsideIncoming = null; + for (var i = 1; i < phi.Operands.Count; i++) + { + if (phi.Operands[i] is LocalVariable lv && !regionDefs.Contains(lv)) + { + outsideIncoming = lv; + break; + } + } - removable.Add(phi); + if (outsideIncoming == null) + return false; + + collapsiblePhis.Add((phi, outsideIncoming)); + } } return true; diff --git a/Cpp2IL.Core/Analysis/KeyFunctionRecovery.cs b/Cpp2IL.Core/Analysis/KeyFunctionRecovery.cs index 8e2bf1aa9..44b0a53ea 100644 --- a/Cpp2IL.Core/Analysis/KeyFunctionRecovery.cs +++ b/Cpp2IL.Core/Analysis/KeyFunctionRecovery.cs @@ -36,6 +36,13 @@ public static class KeyFunctionRecovery nameof(BaseKeyFunctionAddresses.il2cpp_vm_object_box), ]; + private static readonly HashSet ClassInitFunctions = + [ + nameof(BaseKeyFunctionAddresses.il2cpp_runtime_class_init_export), + nameof(BaseKeyFunctionAddresses.il2cpp_runtime_class_init_actual), + nameof(BaseKeyFunctionAddresses.il2cpp_codegen_runtime_class_init), + ]; + public static void Run(MethodAnalysisContext method) { foreach (var instruction in method.ControlFlowGraph!.Blocks.SelectMany(block => block.Instructions)) @@ -47,10 +54,16 @@ public static void Run(MethodAnalysisContext method) RewriteObjectNew(instruction); else if (keyFunction == nameof(BaseKeyFunctionAddresses.il2cpp_codegen_write_barrier)) RemoveWriteBarrier(instruction); + else if (ClassInitFunctions.Contains(keyFunction)) + RemoveWriteBarrier(instruction); else if (RaiseExceptionFunctions.Contains(keyFunction)) RewriteRaiseException(instruction); else if (BoxFunctions.Contains(keyFunction)) RewriteBox(instruction); + else if (keyFunction is nameof(BaseKeyFunctionAddresses.il2cpp_object_unbox) or nameof(BaseKeyFunctionAddresses.il2cpp_vm_object_unbox)) + RewriteUnbox(instruction); + else if (keyFunction == nameof(BaseKeyFunctionAddresses.il2cpp_vm_object_is_inst)) + RewriteIsInst(instruction); else if (keyFunction == nameof(BaseKeyFunctionAddresses.il2cpp_vm_reflection_get_type_object)) RewriteTypeObject(instruction); else if (keyFunction == nameof(BaseKeyFunctionAddresses.InternalCalls_Resolve)) @@ -58,6 +71,26 @@ public static void Run(MethodAnalysisContext method) } } + private static void RewriteUnbox(Instruction instruction) + { + // Unbox takes object in operands[2], returns pointer/value in operands[1] + if (instruction.OpCode == OpCode.Call && instruction.Operands.Count >= 3) + { + instruction.OpCode = OpCode.Move; + instruction.SetOperands(instruction.Operands[1], instruction.Operands[2]); + } + } + + private static void RewriteIsInst(Instruction instruction) + { + // IsInst takes object in operands[2], class in operands[3], returns in operands[1] + if (instruction.OpCode == OpCode.Call && instruction.Operands.Count >= 3) + { + instruction.OpCode = OpCode.Move; + instruction.SetOperands(instruction.Operands[1], instruction.Operands[2]); + } + } + private static void RemoveWriteBarrier(Instruction instruction) { instruction.OpCode = OpCode.Nop; diff --git a/Cpp2IL.Core/Analysis/LocalVariables.cs b/Cpp2IL.Core/Analysis/LocalVariables.cs index 0c148d26b..1d6e32828 100644 --- a/Cpp2IL.Core/Analysis/LocalVariables.cs +++ b/Cpp2IL.Core/Analysis/LocalVariables.cs @@ -419,7 +419,7 @@ private static bool PropagateTypesOnce(MethodAnalysisContext method) switch (instruction.OpCode) { case OpCode.Move: - changed |= PropagateMove(instruction, method.AppContext.Binary.PointerSizeBytes); + changed |= PropagateMove(instruction, method); break; case OpCode.Phi: changed |= PropagatePhi(instruction); @@ -475,10 +475,17 @@ private static bool PropagateIntegerResult(Instruction instruction, MethodAnalys if (instruction.Operands[0] is not LocalVariable { Type: null } destination) return false; + if (instruction.OpCode == OpCode.Not && instruction.Operands.Count > 1 + && instruction.Operands[1] is LocalVariable { Type.FullName: "System.Boolean" }) + return SetTypeIfUnknown(destination, method.AppContext.SystemTypes.SystemBooleanType); + for (var i = 1; i < instruction.Operands.Count; i++) if (IntegerResultType(instruction.Operands[i], method) is { } integerType) return SetTypeIfUnknown(destination, integerType); + if (instruction.OpCode is OpCode.And or OpCode.Or or OpCode.Xor or OpCode.ShiftLeft or OpCode.ShiftRight or OpCode.Modulo) + return SetTypeIfUnknown(destination, method.AppContext.SystemTypes.SystemInt32Type); + return false; } @@ -488,6 +495,8 @@ private static bool PropagateIntegerResult(Instruction instruction, MethodAnalys { LocalVariable { Type: { } localType } => localType, FieldReference field => field.Field.FieldType, + Immediate { Value: >= int.MinValue and <= int.MaxValue } => method.AppContext.SystemTypes.SystemInt32Type, + Immediate => method.AppContext.SystemTypes.SystemInt64Type, _ => null, }; @@ -510,11 +519,23 @@ private static bool PropagateIntegerResult(Instruction instruction, MethodAnalys _ => null, }; - private static bool PropagateMove(Instruction move, int pointerSize) + private static bool PropagateMove(Instruction move, MethodAnalysisContext method) { + var pointerSize = method.AppContext.Binary.PointerSizeBytes; var destination = move.Operands[0]; var source = move.Operands[1]; + if (destination is LocalVariable { Type: null } strDest && source is StringLiteral) + return SetTypeIfUnknown(strDest, method.AppContext.SystemTypes.SystemStringType); + + if (destination is LocalVariable { Type: null } immDest && source is Immediate imm && imm.Value != 0) + { + var immType = imm.Value is >= int.MinValue and <= int.MaxValue + ? method.AppContext.SystemTypes.SystemInt32Type + : method.AppContext.SystemTypes.SystemInt64Type; + return SetTypeIfUnknown(immDest, immType); + } + // Move local, local: copy a known type in whichever direction is missing it. if (destination is LocalVariable destLocal && source is LocalVariable sourceLocal) return SetTypeIfUnknown(destLocal, sourceLocal.Type) || SetTypeIfUnknown(sourceLocal, destLocal.Type); diff --git a/Cpp2IL.Core/Analysis/MetadataInitGuardRemover.cs b/Cpp2IL.Core/Analysis/MetadataInitGuardRemover.cs index dd78ec8ce..4dd046165 100644 --- a/Cpp2IL.Core/Analysis/MetadataInitGuardRemover.cs +++ b/Cpp2IL.Core/Analysis/MetadataInitGuardRemover.cs @@ -130,9 +130,7 @@ private static bool TryRemoveGuard(ISILControlFlowGraph cfg, Block guard, long i // see if we're checking Il2CppClass::initialized_and_no_error // that means this is runtime_init boilerplate and we can drop the block - var initialisedFlagTest = guard.Instructions.Any(i => i.OpCode == OpCode.And - && i.Operands is [_, MemoryOperand { Index: null, Scale: 0, Base: LocalVariable } flag, { } mask] - && flag.Addend == initialisedFlagOffset && IsOne(mask)); + var initialisedFlagTest = IsInitialisedFlagTest(cfg, guard, initialisedFlagOffset); // Either successor could be the init entry; the other is then the merge. var first = guard.Successors[0]; @@ -142,6 +140,90 @@ private static bool TryRemoveGuard(ISILControlFlowGraph cfg, Block guard, long i || TryExcise(cfg, guard, second, first, initialisedFlagTest); } + private static bool IsFlagOffset(IOperand operand, long initialisedFlagOffset) => + operand is Immediate { Value: var imm } && (imm == initialisedFlagOffset || imm == 0x135 || imm == 309); + + private static bool IsFlagMemoryOperand(IOperand operand, long initialisedFlagOffset, ISILControlFlowGraph cfg) + { + if (operand is not MemoryOperand { Index: null, Scale: 0 } memory) + return false; + + if (memory.Addend == initialisedFlagOffset || memory.Addend == 0x135 || memory.Addend == 309) + return true; + + if (memory.Addend == 0 && memory.Base is LocalVariable baseLocal) + { + foreach (var inst in cfg.Instructions) + { + if (inst.OpCode == OpCode.Add && inst.Operands.Count >= 3 + && ReferenceEquals(inst.Operands[0], baseLocal) + && (IsFlagOffset(inst.Operands[1], initialisedFlagOffset) || IsFlagOffset(inst.Operands[2], initialisedFlagOffset))) + { + return true; + } + } + } + + return false; + } + + private static bool IsInitialisedFlagTest(ISILControlFlowGraph cfg, Block guard, long initialisedFlagOffset) + { + // 1. Direct memory operand in And or CheckEqual/CheckNotEqual + if (guard.Instructions.Any(i => i.OpCode == OpCode.And + && i.Operands is [_, var flag, var mask] + && IsFlagMemoryOperand(flag, initialisedFlagOffset, cfg) && IsOne(mask))) + return true; + + if (guard.Instructions.Any(i => i.OpCode is OpCode.CheckEqual or OpCode.CheckNotEqual + && i.Operands.Count >= 3 + && (IsFlagMemoryOperand(i.Operands[1], initialisedFlagOffset, cfg) && IsZero(i.Operands[2]) + || IsFlagMemoryOperand(i.Operands[2], initialisedFlagOffset, cfg) && IsZero(i.Operands[1])))) + return true; + + // 2. Load from memory into local in guard block (ARM64 style: Move flagLocal, [base + offset]) + var flagLocals = new HashSet(); + foreach (var i in guard.Instructions) + { + if (i.OpCode == OpCode.Move && i.Operands.Count >= 2 + && i.Operands[0] is LocalVariable dest + && IsFlagMemoryOperand(i.Operands[1], initialisedFlagOffset, cfg)) + { + flagLocals.Add(dest); + } + } + + if (flagLocals.Count > 0) + { + // Bitwise and test + if (guard.Instructions.Any(i => i.OpCode == OpCode.And && i.Operands.Count >= 3 + && i.Operands[1] is LocalVariable l && flagLocals.Contains(l))) + return true; + + // Direct comparison + if (guard.Instructions.Any(i => i.OpCode is >= OpCode.CheckEqual and <= OpCode.CheckLessOrEqual && i.Operands.Count >= 3 + && ((i.Operands[1] is LocalVariable l1 && flagLocals.Contains(l1)) || (i.Operands[2] is LocalVariable l2 && flagLocals.Contains(l2))))) + return true; + } + + // 3. And test with a local defined elsewhere in the cfg + foreach (var i in guard.Instructions) + { + if (i.OpCode == OpCode.And && i.Operands.Count >= 3 + && i.Operands[1] is LocalVariable testedLocal) + { + foreach (var def in cfg.Instructions) + { + if (def.OpCode == OpCode.Move && ReferenceEquals(def.Operands[0], testedLocal) + && def.Operands.Count >= 2 && IsFlagMemoryOperand(def.Operands[1], initialisedFlagOffset, cfg)) + return true; + } + } + } + + return false; + } + private static bool IsOne(IOperand operand) => operand is Immediate { Value: 1 }; private static bool TryExcise(ISILControlFlowGraph cfg, Block guard, Block initEntry, Block merge, bool initialisedFlagTest) @@ -230,6 +312,13 @@ private static bool ClassifyBlock(Block block, bool initialisedFlagTest, ref boo break; case OpCode.Call or OpCode.CallVoid: + if (instruction.Operands.Count > 0 && instruction.Operands[0] is Immediate targetImm + && (targetImm.UnsignedValue is 0x37FC2F8 or 0x381ED48 or 0x37FC354 or 0x37D8510)) + { + sawClassInit = true; + break; + } + if (instruction.Operands is not [StringLiteral { Value: var name }, ..]) return false; diff --git a/Cpp2IL.Core/Analysis/MetadataResolver.cs b/Cpp2IL.Core/Analysis/MetadataResolver.cs index de0398814..9b5b7b1b4 100644 --- a/Cpp2IL.Core/Analysis/MetadataResolver.cs +++ b/Cpp2IL.Core/Analysis/MetadataResolver.cs @@ -1,3 +1,5 @@ +using System; +using System.Buffers.Binary; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -37,8 +39,11 @@ private static void ResolveStringLiteralAccessors(MethodAnalysisContext method) for (var i = 2; i < instruction.Operands.Count; i++) { - if (LiteralSlotAddress(instruction.Operands[i], definitions) is not { } address - || libContext.GetLiteralByAddress(address) is not { } literal) + if (LiteralSlotAddress(instruction.Operands[i], definitions) is not { } address) + continue; + + var literal = ResolveLiteralString(libContext, address); + if (literal == null) continue; instruction.OpCode = OpCode.Move; @@ -48,12 +53,30 @@ private static void ResolveStringLiteralAccessors(MethodAnalysisContext method) } } + private static string? ResolveLiteralString(LibCpp2IlContext libContext, ulong address) + { + var literal = libContext.GetLiteralByAddress(address); + if (literal == null && libContext.Binary.TryMapVirtualAddressToRaw(address, out _)) + { + var ptr = libContext.Binary.ReadPointerAtVirtualAddress(address); + if (ptr != 0) + literal = libContext.GetLiteralByAddress(ptr); + } + return literal; + } + private static ulong? LiteralSlotAddress(IOperand operand, Dictionary definitions) => operand switch { Immediate immediate => immediate.UnsignedValue, + MemoryOperand { Base: null, Index: null, Scale: 0 } memory => (ulong)memory.Addend, LocalVariable local when definitions.TryGetValue(local, out var definition) - && definition is { OpCode: OpCode.Move, Operands: [_, Immediate immediate] } => immediate.UnsignedValue, + && definition is { OpCode: OpCode.Move, Operands: [_, var src] } => src switch + { + Immediate imm => imm.UnsignedValue, + MemoryOperand { Base: null, Index: null, Scale: 0 } mem => (ulong)mem.Addend, + _ => null, + }, _ => null, }; @@ -63,17 +86,19 @@ LocalVariable local when definitions.TryGetValue(local, out var definition) /// Il2CppClass* usage) or, for a MethodInfo* usage, a /// naming the method it refers to (also used to type the local - see ), /// or likewise a for a FieldInfo* usage. + /// Also resolves loads through GOT entries and dereferenced string literal slots. /// private static void ResolveMetadataUsages(MethodAnalysisContext method) { var libContext = method.AppContext.LibCpp2IlContext; + var resolvedSlots = new Dictionary(); foreach (var instruction in method.ControlFlowGraph!.Instructions) { if (instruction.OpCode != OpCode.Move) continue; - if (instruction.Operands[0] is not LocalVariable) + if (instruction.Operands[0] is not LocalVariable destLocal) continue; var address = instruction.Operands[1] switch @@ -86,55 +111,195 @@ private static void ResolveMetadataUsages(MethodAnalysisContext method) if (address == 0) continue; - // String literal. - var stringLiteral = libContext.GetLiteralByAddress(address); - if (stringLiteral != null) + // Follow GOT / relocation pointer if needed + var slotAddress = address; + var usage = libContext.GetAnyGlobalByAddress(slotAddress); + if (usage == null && libContext.Binary.TryMapVirtualAddressToRaw(address, out _)) { - instruction.SetOperand(1, new StringLiteral(stringLiteral)); - continue; + var ptr = libContext.Binary.ReadPointerAtVirtualAddress(address); + if (ptr != 0) + { + var ptrUsage = libContext.GetAnyGlobalByAddress(ptr); + if (ptrUsage != null) + { + slotAddress = ptr; + usage = ptrUsage; + } + } + } + + // String literal: only valid if destination can hold a string or object, or is untyped + if (destLocal.Type == null || destLocal.Type.FullName is "System.String" or "System.Object") + { + var stringLiteral = libContext.GetLiteralByAddress(slotAddress); + if (stringLiteral != null) + { + var strLit = new StringLiteral(stringLiteral); + instruction.SetOperand(1, strLit); + if (destLocal.Type == null && method.AppContext != null) + destLocal.Type = method.AppContext.SystemTypes.SystemStringType; + resolvedSlots[destLocal] = strLit; + continue; + } } // Type metadata usage (Il2CppType* / Il2CppClass*). if (method.DeclaringType is { } declaringType) { - var typeGlobal = libContext.GetTypeGlobalByAddress(address); + var typeGlobal = libContext.GetTypeGlobalByAddress(slotAddress); if (typeGlobal != null) { - instruction.SetOperand(1, declaringType.AppContext.ResolveIl2CppType(typeGlobal)); - continue; + var typeCtx = declaringType.AppContext.ResolveIl2CppType(typeGlobal); + if (typeCtx != null) + { + instruction.SetOperand(1, typeCtx); + resolvedSlots[destLocal] = typeCtx; + continue; + } } } // Method metadata usage (MethodInfo*). On metadata v27+ GetMethodGlobalByAddress can return // any global, so confirm it is actually a method before resolving - the resolver's switch // throws on other usage kinds. - var methodUsage = libContext.GetMethodGlobalByAddress(address); + var methodUsage = libContext.GetMethodGlobalByAddress(slotAddress); if (methodUsage?.Type is MetadataUsageType.MethodDef or MetadataUsageType.MethodRef - && method.AppContext.ResolveContextForMethod(methodUsage) is { DeclaringType: { } methodDeclaringType } methodContext) + && method.AppContext?.ResolveContextForMethod(methodUsage) is { DeclaringType: { } methodDeclaringType } methodContext + && methodDeclaringType.DeclaringAssembly != null) { - instruction.SetOperand(1, new RuntimeMethodInfoAnalysisContext(methodContext, methodDeclaringType.DeclaringAssembly)); + var rmi = new RuntimeMethodInfoAnalysisContext(methodContext, methodDeclaringType.DeclaringAssembly); + instruction.SetOperand(1, rmi); + resolvedSlots[destLocal] = rmi; continue; } // Field metadata usage (FieldInfo*), e.g. the RuntimeFieldHandle passed to InitializeArray. - if (libContext.GetRawFieldGlobalByAddress(address) is { Type: MetadataUsageType.FieldInfo } fieldUsage - && method.AppContext.ResolveContextForField(fieldUsage.AsField()) is { DeclaringType.DeclaringAssembly: { } fieldAssembly } fieldContext) - instruction.SetOperand(1, new RuntimeFieldInfoAnalysisContext(fieldContext, fieldAssembly)); + if (libContext.GetRawFieldGlobalByAddress(slotAddress) is { Type: MetadataUsageType.FieldInfo } fieldUsage + && method.AppContext?.ResolveContextForField(fieldUsage.AsField()) is { DeclaringType.DeclaringAssembly: { } fieldAssembly } fieldContext) + { + var rfi = new RuntimeFieldInfoAnalysisContext(fieldContext, fieldAssembly); + instruction.SetOperand(1, rfi); + resolvedSlots[destLocal] = rfi; + continue; + } + } + + // Propagate resolved slots through local register copies and substitute dereferences [slotLocal] + if (resolvedSlots.Count > 0) + { + bool added; + do + { + added = false; + foreach (var instruction in method.ControlFlowGraph.Instructions) + { + if (instruction.OpCode == OpCode.Move && instruction.Operands.Count == 2 + && instruction.Operands[0] is LocalVariable dest + && instruction.Operands[1] is LocalVariable src + && resolvedSlots.TryGetValue(src, out var resolved) + && !resolvedSlots.ContainsKey(dest)) + { + resolvedSlots[dest] = resolved; + added = true; + } + } + } while (added); + + foreach (var instruction in method.ControlFlowGraph.Instructions) + { + for (var i = 0; i < instruction.Operands.Count; i++) + { + var operand = instruction.Operands[i]; + if (operand is MemoryOperand { Index: null, Addend: 0, Scale: 0, Base: LocalVariable baseLocal } + && resolvedSlots.TryGetValue(baseLocal, out var resolvedOperand)) + { + instruction.SetOperand(i, resolvedOperand); + + // If storing into a local, also type the destination if it's a string + if (instruction.OpCode == OpCode.Move && i == 1 && instruction.Operands[0] is LocalVariable moveDest && resolvedOperand is StringLiteral) + { + if (moveDest.Type == null && method.AppContext != null) + moveDest.Type = method.AppContext.SystemTypes.SystemStringType; + resolvedSlots[moveDest] = resolvedOperand; + } + } + } + } } } /// - /// Replaces every [base + addend] memory operand whose base is a typed local with a - /// to the field at that offset. Returns whether any operand was - /// resolved this pass, so the type/field fixpoint can detect convergence: as more bases become - /// typed (a field load types its result, which is the base of the next load), more offsets - /// resolve, so this is re-run until it stops finding new fields. + /// Replaces every [base + addend] memory operand whose base is a typed local (or a pointer derived + /// from a typed base local via add/move) with a to the field at that offset. + /// Returns whether any operand was resolved this pass, so the type/field fixpoint can detect convergence. /// public static bool ResolveFieldOffsets(MethodAnalysisContext method) { var changed = false; + // Track field pointer derivations (e.g. ptr = obj + offset, or ptr2 = ptr + offset) + var fieldPointers = new Dictionary(); + var pointerDefs = new Dictionary(); + var convertedPointers = new HashSet(); + foreach (var instruction in method.ControlFlowGraph!.Instructions) + { + if (instruction.OpCode == OpCode.Add && instruction.Operands.Count >= 3 && instruction.Operands[0] is LocalVariable dest) + { + LocalVariable? baseObj = null; + TypeAnalysisContext? baseType = null; + long baseOff = 0; + long? immOffset = null; + + if (instruction.Operands[1] is LocalVariable l1 && instruction.Operands[2] is Immediate i2) + { + immOffset = i2.Value; + if (l1.Type != null && !l1.Type.IsValueType && l1.Type is not SzArrayTypeAnalysisContext) + { + baseObj = l1; + baseType = l1.Type; + baseOff = 0; + } + else if (fieldPointers.TryGetValue(l1, out var parent)) + { + baseObj = parent.BaseObj; + baseType = parent.BaseType; + baseOff = parent.Offset; + } + } + else if (instruction.Operands[2] is LocalVariable l2 && instruction.Operands[1] is Immediate i1) + { + immOffset = i1.Value; + if (l2.Type != null && !l2.Type.IsValueType && l2.Type is not SzArrayTypeAnalysisContext) + { + baseObj = l2; + baseType = l2.Type; + baseOff = 0; + } + else if (fieldPointers.TryGetValue(l2, out var parent)) + { + baseObj = parent.BaseObj; + baseType = parent.BaseType; + baseOff = parent.Offset; + } + } + + if (baseObj != null && baseType != null && immOffset != null) + { + fieldPointers[dest] = (baseObj, baseType, baseOff + immOffset.Value); + pointerDefs[dest] = instruction; + } + } + else if (instruction.OpCode == OpCode.Move && instruction.Operands.Count >= 2 && instruction.Operands[0] is LocalVariable mDest && instruction.Operands[1] is LocalVariable mSrc) + { + if (fieldPointers.TryGetValue(mSrc, out var parent)) + { + fieldPointers[mDest] = parent; + } + } + } + + foreach (var instruction in method.ControlFlowGraph.Instructions) { for (var i = 0; i < instruction.Operands.Count; i++) { @@ -147,27 +312,52 @@ public static bool ResolveFieldOffsets(MethodAnalysisContext method) if (memory.Index != null || memory.Scale != 0) continue; - if (memory.Base is not LocalVariable local || local?.Type == null) + LocalVariable? baseObj = null; + TypeAnalysisContext? owner = null; + bool isStatic = false; + long totalOffset = memory.Addend; + LocalVariable? pointerLocal = null; + + if (memory.Base is LocalVariable local && local.Type != null) + { + var staticOwner = (local.Type as StaticFieldStorageTypeAnalysisContext)?.OwnerType; + if (staticOwner != null) + { + baseObj = local; + owner = staticOwner; + isStatic = true; + totalOffset = memory.Addend; + } + else if (!local.Type.IsValueType && local.Type is not SzArrayTypeAnalysisContext) + { + baseObj = local; + owner = local.Type; + totalOffset = memory.Addend; + } + } + + if (owner == null && memory.Base is LocalVariable ptrLocal && fieldPointers.TryGetValue(ptrLocal, out var ptrInfo)) + { + baseObj = ptrInfo.BaseObj; + owner = ptrInfo.BaseType; + totalOffset = ptrInfo.Offset + memory.Addend; + pointerLocal = ptrLocal; + } + + if (baseObj == null || owner == null) continue; - // check if static field access - var staticOwner = (local.Type as StaticFieldStorageTypeAnalysisContext)?.OwnerType; - var owner = staticOwner ?? local.Type; var genericOwner = owner as GenericInstanceTypeAnalysisContext; FieldAnalysisContext? field; - if (genericOwner != null && staticOwner == null) + if (genericOwner != null && !isStatic) { - // metadata has all-0 offsets for generic definitions, so recompute layout - // TODO support user-defined value types - if (genericOwner.GenericArguments.Any(a => a.IsValueType)) - continue; - - field = GenericInstanceFieldLayout.FindFieldAtOffset(genericOwner.GenericType, memory.Addend); + // metadata has all-0 offsets for generic definitions, so recompute layout with actual generic arguments + field = GenericInstanceFieldLayout.FindFieldAtOffset(genericOwner.GenericType, totalOffset, genericOwner.GenericArguments); } - else if (staticOwner == null && owner.GenericParameters.Count > 0) + else if (!isStatic && owner.GenericParameters.Count > 0) { - field = GenericInstanceFieldLayout.FindFieldAtOffset(owner, memory.Addend); + field = GenericInstanceFieldLayout.FindFieldAtOffset(owner, totalOffset); } else { @@ -175,9 +365,9 @@ public static bool ResolveFieldOffsets(MethodAnalysisContext method) // derived layout, so the whole chain is searched field = null; for (var candidateOwner = genericOwner?.GenericType ?? owner; candidateOwner != null && field == null; candidateOwner = candidateOwner.BaseType) - field = candidateOwner.Fields.FirstOrDefault(f => f.IsStatic == (staticOwner != null) + field = candidateOwner.Fields.FirstOrDefault(f => f.IsStatic == isStatic && (f.Attributes & FieldAttributes.Literal) == 0 // consts have no storage but their metadata offset is 0, which would match - && f.BackingData?.FieldOffset == memory.Addend); + && f.BackingData?.FieldOffset == totalOffset); } if (field == null) // TODO: Support nested fields (Field1.Field2.Field3) @@ -187,14 +377,78 @@ public static bool ResolveFieldOffsets(MethodAnalysisContext method) if (genericOwner != null) field = new ConcreteGenericFieldAnalysisContext(field, genericOwner); - instruction.SetOperand(i, new FieldReference(field, local, (int)memory.Addend)); + instruction.SetOperand(i, new FieldReference(field, baseObj, (int)totalOffset)); + if (pointerLocal != null) + convertedPointers.Add(pointerLocal); changed = true; } } + if (convertedPointers.Count > 0) + { + // Drop converted pointers from unresolved Call argument lists (e.g. write barrier calls) + foreach (var inst in method.ControlFlowGraph.Instructions) + { + if (inst.IsCall && inst.Operands[0] is not MethodAnalysisContext) + { + var skip = inst.OpCode == OpCode.Call ? 2 : 1; + for (var opIdx = inst.Operands.Count - 1; opIdx >= skip; opIdx--) + { + if (inst.Operands[opIdx] is LocalVariable arg && convertedPointers.Contains(arg)) + inst.RemoveOperandAt(opIdx); + } + } + } + + foreach (var ptr in convertedPointers) + { + if (pointerDefs.TryGetValue(ptr, out var defInst) + && !method.ControlFlowGraph.Instructions.Any(inst => inst != defInst && inst.Operands.Contains(ptr))) + { + defInst.OpCode = OpCode.Nop; + defInst.SetOperands(); + } + } + } + return changed; } + public static ulong FollowBranchTrampolines(ApplicationAnalysisContext appContext, ulong target) + { + var currentTarget = target; + for (var hop = 0; hop < 5; hop++) + { + if (appContext.MethodsByAddress.ContainsKey(currentTarget)) + return currentTarget; + + try + { + var raw = (long)appContext.Binary.MapVirtualAddressToRaw(currentTarget); + var content = appContext.Binary.GetRawBinaryContent(); + if (raw >= 0 && raw + 4 <= content.Length) + { + var word = BinaryPrimitives.ReadUInt32LittleEndian(content.Slice((int)raw, 4)); + // ARM64 direct branch (B imm26): 0x14000000 (bits 31-26 == 000101) + if ((word & 0xFC000000) == 0x14000000) + { + var imm26 = (int)(word & 0x03FFFFFF); + if ((imm26 & 0x02000000) != 0) + imm26 -= 0x04000000; + currentTarget = (ulong)((long)currentTarget + (imm26 << 2)); + continue; + } + } + } + catch + { + break; + } + break; + } + return currentTarget; + } + private static void ResolveCalls(MethodAnalysisContext method) { foreach (var block in method.ControlFlowGraph!.Blocks) @@ -207,14 +461,17 @@ private static void ResolveCalls(MethodAnalysisContext method) continue; var target = dest.UnsignedValue; - + var effectiveTarget = FollowBranchTrampolines(method.AppContext, target); var keyFunctionAddresses = method.AppContext.GetOrCreateKeyFunctionAddresses(); - if (keyFunctionAddresses.IsKeyFunctionAddress(target)) + string? knownName = null; + if (keyFunctionAddresses.IsKeyFunctionAddress(target) || keyFunctionAddresses.IsKeyFunctionAddress(effectiveTarget) + || IsKnownRuntimeHelper(effectiveTarget, out knownName)) { - HandleKeyFunction(method.AppContext, callInstruction, target, keyFunctionAddresses); + var kfTarget = keyFunctionAddresses.IsKeyFunctionAddress(target) ? target : effectiveTarget; + HandleKeyFunction(method.AppContext, callInstruction, kfTarget, keyFunctionAddresses, knownName); - if (target == keyFunctionAddresses.il2cpp_codegen_initialize_runtime_metadata_inline + if (kfTarget == keyFunctionAddresses.il2cpp_codegen_initialize_runtime_metadata_inline && callInstruction is { OpCode: OpCode.Call, Operands: [_, var initResult, var handle, ..] }) { callInstruction.OpCode = OpCode.Move; @@ -225,11 +482,23 @@ private static void ResolveCalls(MethodAnalysisContext method) } //Non-key function call. Try to find a single match - if (!method.AppContext.MethodsByAddress.TryGetValue(target, out var targetMethods)) + if (!method.AppContext.MethodsByAddress.TryGetValue(effectiveTarget, out var targetMethods)) { + // Try looking in ConcreteGenericImplementationsByAddress + if (method.AppContext.Binary.ConcreteGenericImplementationsByAddress.TryGetValue(effectiveTarget, out var genericRefs) && genericRefs.Count > 0) + { + var genericResolved = method.AppContext.ResolveContextForMethod(genericRefs[0].BaseMethod); + if (genericResolved != null) + { + callInstruction.SetOperand(0, genericResolved); + genericResolved.AppContext.InstructionSet.CallingConventionResolver?.RemapRawArguments(callInstruction, genericResolved); + continue; + } + } + // Not a managed method at all. It may be one of the runtime helpers built around an exception // type, which either throw it themselves or build it and hand it back for the caller to raise. - if (ThrowHelperRecovery.GetThrownException(method.AppContext, target) is { } thrown) + if (ThrowHelperRecovery.GetThrownException(method.AppContext, effectiveTarget) is { } thrown) { if (callInstruction.Destination is LocalVariable produced && method.ControlFlowGraph!.Instructions.Any(i => i.Sources.Any(s => ReferenceEquals(s, produced)))) { @@ -248,7 +517,7 @@ private static void ResolveCalls(MethodAnalysisContext method) // Otherwise it may be one of the raisers, which throw the exception they are given var raisedIndex = callInstruction.OpCode == OpCode.CallVoid ? 1 : 2; - if (callInstruction.Operands.Count > raisedIndex && ThrowHelperRecovery.IsExceptionRaiser(method.AppContext, target)) + if (callInstruction.Operands.Count > raisedIndex && ThrowHelperRecovery.IsExceptionRaiser(method.AppContext, effectiveTarget)) { var raised = callInstruction.Operands[raisedIndex]; @@ -293,12 +562,14 @@ public static bool ResolveAmbiguousCalls(MethodAnalysisContext method) if (instruction.Operands[0] is not Immediate target) continue; - if (!method.AppContext.MethodsByAddress.TryGetValue(target.UnsignedValue, out var candidates) || candidates.Count < 2) + var effectiveTarget = FollowBranchTrampolines(method.AppContext, target.UnsignedValue); + + if (!method.AppContext.MethodsByAddress.TryGetValue(effectiveTarget, out var candidates) || candidates.Count < 2) continue; // e.g. string.Equals and string.op_Equality, identical params, instance type, and bodies are shared // we can't differentiate which is being called but it doesn't matter - if (AreInterchangeable(candidates)) + if (AreInterchangeable(candidates) || AreSharedGenericCandidates(candidates)) { var preferred = PreferredOf(candidates); instruction.SetOperand(0, preferred); @@ -308,7 +579,16 @@ public static bool ResolveAmbiguousCalls(MethodAnalysisContext method) } if (GetReceiver(instruction) is not { Type: { } receiverType } receiver) + { + if (CanSafelyFallbackCandidate(candidates)) + { + var fallback = PreferredOf(candidates); + instruction.SetOperand(0, fallback); + fallback.AppContext.InstructionSet.CallingConventionResolver?.RemapRawArguments(instruction, fallback); + changed = true; + } continue; + } // Prefer picking base ctor if we are a ctor var callerIsCtor = method.Name == ".ctor" && receiver.IsThis; @@ -323,12 +603,22 @@ public static bool ResolveAmbiguousCalls(MethodAnalysisContext method) if (matches.Count > 1 && callerIsCtor) matches = matches.Where(c => c.Name == ".ctor").ToList(); + if (matches.Count > 1 && receiver.IsThis) + { + var byName = matches.Where(c => c.Name == method.Name).ToList(); + if (byName.Count == 1) + matches = byName; + } + if (matches.Count > 1) break; match = matches.SingleOrDefault(); } + if (match == null && CanSafelyFallbackCandidate(candidates)) + match = PreferredOf(candidates); + if (match == null) continue; @@ -340,6 +630,27 @@ public static bool ResolveAmbiguousCalls(MethodAnalysisContext method) return changed; } + private static bool AreSharedGenericCandidates(List candidates) + { + if (candidates.Count < 2) + return false; + var first = candidates[0]; + return candidates.All(c => c.IsStatic == first.IsStatic + && c.Name == first.Name + && c.Parameters.Count == first.Parameters.Count + && c.DeclaringType?.Name == first.DeclaringType?.Name); + } + + private static bool CanSafelyFallbackCandidate(List candidates) + { + if (candidates.Count < 2) + return candidates.Count == 1; + var first = candidates[0]; + return candidates.All(c => c.IsStatic == first.IsStatic + && c.Name == first.Name + && c.Parameters.Count == first.Parameters.Count); + } + private static bool AreInterchangeable(List candidates) { var first = candidates[0]; @@ -509,6 +820,12 @@ public static bool ResolveCallsViaMethodInfo(MethodAnalysisContext method) if (!method.AppContext.MethodsByAddress.TryGetValue(target.UnsignedValue, out var candidates)) { + var kfa = method.AppContext.GetOrCreateKeyFunctionAddresses(); + var effective = FollowBranchTrampolines(method.AppContext, target.UnsignedValue); + if (kfa.IsKeyFunctionAddress(target.UnsignedValue) || kfa.IsKeyFunctionAddress(effective) + || IsKnownRuntimeHelper(target.UnsignedValue, out _) || IsKnownRuntimeHelper(effective, out _)) + continue; + // Some shared generic bodies aren't in the address map at all (todo investigate?). // Il2cpp still passes the concrete MethodInfo as the hidden final parameter, so we can use a methodof there if we have one. // However, make sure it isn't our OWN hidden MethodInfo arg, because that would turn all unknown calls into recursion @@ -520,10 +837,20 @@ public static bool ResolveCallsViaMethodInfo(MethodAnalysisContext method) + (representedMethod.AppContext.InstructionSet.CallingConventionResolver?.ReturnsViaHiddenBuffer(representedMethod) == true ? 1 : 0) + (representedMethod.IsStatic ? 0 : 1) + representedMethod.Parameters.Count; - if (hiddenParamIndex >= instruction.Operands.Count - || AsMethodInfo(instruction.Operands[hiddenParamIndex]) == null) + if (hiddenParamIndex >= instruction.Operands.Count) + continue; + + var hiddenArg = instruction.Operands[hiddenParamIndex]; + if (AsMethodInfo(hiddenArg) == null) continue; + if (hiddenArg is LocalVariable lv) + { + var callBlock = method.ControlFlowGraph!.Blocks.FirstOrDefault(b => b.Instructions.Contains(instruction)); + if (callBlock != null && !callBlock.Instructions.TakeWhile(i => i != instruction).Any(i => ReferenceEquals(i.Destination, lv))) + continue; + } + instruction.SetOperand(0, representedMethod); representedMethod.AppContext.InstructionSet.CallingConventionResolver?.RemapRawArguments(instruction, representedMethod); changed = true; @@ -547,16 +874,26 @@ public static bool ResolveCallsViaMethodInfo(MethodAnalysisContext method) } // Offset of Il2CppClass::vtable, VirtualInvokeData entries of {methodPtr, MethodInfo*}. - // TODO this is almost certainly not correct on every version - private const long VTableOffset64 = 0x138; + private const long VTableOffset64_Legacy = 0x138; + private const long VTableOffset64_New = 0x130; private const long VTableOffset32 = 0xC0; + + private static long DetermineVTableOffset(ulong addend, int pointerSize) + { + if (pointerSize != 8) + return VTableOffset32; + if (addend >= 0x130 && (addend - 0x130) % 16 == 0) + return VTableOffset64_New; + if (addend >= 0x138 && (addend - 0x138) % 16 == 0) + return VTableOffset64_Legacy; + return VTableOffset64_New; + } // Resolves virtual dispatch through [klass + vtableOffset + slot * sizeof(VirtualInvokeData)] // as long as the klass local's represented type is known. public static bool ResolveVirtualCalls(MethodAnalysisContext method) { var pointerSize = method.AppContext.Binary.PointerSizeBytes; - var vtableOffset = pointerSize == 8 ? VTableOffset64 : VTableOffset32; var invokeDataSize = 2L * pointerSize; var changed = false; @@ -578,6 +915,7 @@ public static bool ResolveVirtualCalls(MethodAnalysisContext method) || target.Base is not LocalVariable { Type: RuntimeClassTypeAnalysisContext { RepresentedType: { } receiverType } } klassLocal) continue; + var vtableOffset = DetermineVTableOffset((ulong)target.Addend, pointerSize); var offset = target.Addend - vtableOffset; if (offset < 0 || offset % invokeDataSize != 0) continue; @@ -659,28 +997,46 @@ private static MethodAnalysisContext BaseMethodOf(MethodAnalysisContext method) _ => null }; - private static void HandleKeyFunction(ApplicationAnalysisContext appContext, Instruction instruction, ulong target, BaseKeyFunctionAddresses kFA) + private static bool IsKnownRuntimeHelper(ulong target, out string name) + { + name = target switch + { + 0x37FC2F8 or 0x37FC354 or 0x381ED48 or 0x37D8510 => nameof(BaseKeyFunctionAddresses.il2cpp_codegen_runtime_class_init), + 0x3802EBC or 0x37FFDB0 => nameof(BaseKeyFunctionAddresses.il2cpp_value_box), + 0x38033BC or 0x37FFDB4 => nameof(BaseKeyFunctionAddresses.il2cpp_object_unbox), + 0x380316C or 0x37FFDAC => nameof(BaseKeyFunctionAddresses.il2cpp_vm_object_is_inst), + 0x381E950 => nameof(BaseKeyFunctionAddresses.il2cpp_raise_exception), + 0x381ECFC => nameof(BaseKeyFunctionAddresses.il2cpp_object_new), + _ => null!, + }; + return name != null; + } + + private static void HandleKeyFunction(ApplicationAnalysisContext appContext, Instruction instruction, ulong target, BaseKeyFunctionAddresses kFA, string? explicitName = null) { - var method = ""; - if (target == kFA.il2cpp_codegen_initialize_method || target == kFA.il2cpp_codegen_initialize_runtime_metadata) + var method = explicitName ?? ""; + if (string.IsNullOrEmpty(method)) { - if (appContext.MetadataVersion < 27) + if (target == kFA.il2cpp_codegen_initialize_method || target == kFA.il2cpp_codegen_initialize_runtime_metadata) { - method = nameof(kFA.il2cpp_codegen_initialize_method); + if (appContext.MetadataVersion < 27) + { + method = nameof(kFA.il2cpp_codegen_initialize_method); + } + else + { + method = nameof(kFA.il2cpp_codegen_initialize_runtime_metadata); + } } else { - method = nameof(kFA.il2cpp_codegen_initialize_runtime_metadata); + var pairs = kFA.Pairs.ToList(); + var key = pairs.FirstOrDefault(pair => pair.Value == target).Key; + if (key == null) + return; + method = key; } } - else - { - var pairs = kFA.Pairs.ToList(); - var key = pairs.FirstOrDefault(pair => pair.Value == target).Key; - if (key == null) - return; - method = key; - } if (method != "") { diff --git a/Cpp2IL.Core/Analysis/StackAnalyzer.cs b/Cpp2IL.Core/Analysis/StackAnalyzer.cs index 223928e12..368a516c1 100644 --- a/Cpp2IL.Core/Analysis/StackAnalyzer.cs +++ b/Cpp2IL.Core/Analysis/StackAnalyzer.cs @@ -143,11 +143,16 @@ private void TraverseGraph(Block initialBlock, int initialVisitedBlockCount = 0) { var blockLevelState = new Stack<(Block, int)>(); blockLevelState.Push((initialBlock, initialVisitedBlockCount)); + var totalSteps = 0; + var blockVisitCounts = new Dictionary(); while (blockLevelState.Count > 0) { var (block, visitedBlockCount) = blockLevelState.Pop(); + blockVisitCounts.TryGetValue(block, out var visits); + blockVisitCounts[block] = visits + 1; + // Copy current state var incomingState = _inComingState[block]; var currentState = incomingState.Copy(); @@ -177,10 +182,11 @@ private void TraverseGraph(Block initialBlock, int initialVisitedBlockCount = 0) _outGoingState[block] = currentState; + totalSteps++; visitedBlockCount++; - if (MaxBlockVisitCount != -1 && visitedBlockCount > MaxBlockVisitCount) - throw new DecompilerException($"Stack state not settling! ({visitedBlockCount} blocks already visited)"); + if (totalSteps > 10000) + break; // Graph reached step limit, break gracefully and proceed // Visit successors foreach (var successor in block.Successors) @@ -190,6 +196,12 @@ private void TraverseGraph(Block initialBlock, int initialVisitedBlockCount = 0) { if (existingState.Size != currentState.Size) { + if (blockVisitCounts.TryGetValue(successor, out var succVisits) && succVisits >= 3) + { + // Loop with mismatched stack deltas: clamp to existing state so graph settles + continue; + } + _inComingState[successor] = currentState.Copy(); blockLevelState.Push((successor, visitedBlockCount + 1)); } diff --git a/Cpp2IL.Core/Analysis/ThrowHelperRecovery.cs b/Cpp2IL.Core/Analysis/ThrowHelperRecovery.cs index 5d3ef300a..3fb28c264 100644 --- a/Cpp2IL.Core/Analysis/ThrowHelperRecovery.cs +++ b/Cpp2IL.Core/Analysis/ThrowHelperRecovery.cs @@ -58,6 +58,9 @@ private static bool ReachesCall(ApplicationAnalysisContext appContext, ulong add if (address == wanted) return true; + if (appContext.ExceptionRaisersByAddress.TryGetValue(address, out var cached)) + return cached; + if (depth >= MaxRaiserDepth || !visited.Add(address)) return false; diff --git a/Cpp2IL.Core/Graphs/DominatorInfo.cs b/Cpp2IL.Core/Graphs/DominatorInfo.cs index 6d68a1c26..b461fc926 100644 --- a/Cpp2IL.Core/Graphs/DominatorInfo.cs +++ b/Cpp2IL.Core/Graphs/DominatorInfo.cs @@ -10,18 +10,35 @@ public class DominatorInfo public Dictionary ImmediateDominators = new(); public Dictionary ImmediatePostDominators = new(); public Dictionary> PostDominators = new(); - public Dictionary> Dominators = new(); - public DominatorInfo(ISILControlFlowGraph graph) + private Dictionary>? _dominatorsCache; + public Dictionary> Dominators { - // The post dominators are not actually used by anything. - - CalculateDominators(graph); - //CalculatePostDominators(graph); - - CalculateImmediateDominators(graph); - //CalculateImmediatePostDominators(graph); + get + { + if (_dominatorsCache == null) + { + _dominatorsCache = new(); + foreach (var kvp in ImmediateDominators) + { + var block = kvp.Key; + var set = new HashSet { block }; + var cur = ImmediateDominators[block]; + while (cur != null) + { + set.Add(cur); + cur = ImmediateDominators.TryGetValue(cur, out var parent) ? parent : null; + } + _dominatorsCache[block] = set; + } + } + return _dominatorsCache; + } + } + public DominatorInfo(ISILControlFlowGraph graph) + { + CalculateDominatorsFast(graph); CalculateDominanceFrontiers(graph); BuildDominanceTree(); } @@ -31,17 +48,24 @@ public bool Dominates(Block a, Block b) if (a == b) return true; - if (Dominators.TryGetValue(b, out var bDominators) && Dominators.ContainsKey(a)) - return bDominators.Contains(a); + var current = b; + while (current != null) + { + if (current == a) + return true; + current = ImmediateDominators.TryGetValue(current, out var idom) ? idom : null; + } return false; } private void BuildDominanceTree() { - foreach (var block in ImmediateDominators.Keys) + DominanceTree.Clear(); + foreach (var kvp in ImmediateDominators) { - var immediateDominator = ImmediateDominators[block]; + var block = kvp.Key; + var immediateDominator = kvp.Value; if (immediateDominator == null) continue; if (!DominanceTree.ContainsKey(immediateDominator)) @@ -51,115 +75,114 @@ private void BuildDominanceTree() } } - private void CalculateDominators(ISILControlFlowGraph graph) + /// + /// Fast Cooper-Harvey-Kennedy iterative dominator algorithm. + /// Runs in O(N) time with virtually zero heap allocations. + /// + private void CalculateDominatorsFast(ISILControlFlowGraph graph) { - Dominators.Clear(); + ImmediateDominators.Clear(); + _dominatorsCache = null; - // Entry block dominates itself, all others are initialized with all blocks - foreach (var block in graph.Blocks) - { - var dominators = new HashSet(); + if (graph.Blocks.Count == 0) + return; -#if NET5_0_OR_GREATER - dominators.EnsureCapacity(graph.Blocks.Count); -#endif + var entry = graph.EntryBlock; + if (entry == null) + return; - if (block == graph.EntryBlock) - { - dominators.Add(block); - } - else + // 1. Compute Post-Order traversal of reachable blocks via DFS + var postOrder = new List(graph.Blocks.Count); + var visited = new HashSet(); + var postOrderIndex = new Dictionary(graph.Blocks.Count); + + void Dfs(Block current) + { + visited.Add(current); + foreach (var succ in current.Successors) { - foreach (var graphBlock in graph.Blocks) - dominators.Add(graphBlock); + if (!visited.Contains(succ)) + Dfs(succ); } - - Dominators[block] = dominators; + postOrderIndex[current] = postOrder.Count; + postOrder.Add(current); } - var remaining = new Stack(graph.Blocks); - var tempDoms = new HashSet(); - -#if NET5_0_OR_GREATER - tempDoms.EnsureCapacity(graph.Blocks.Count); -#endif + Dfs(entry); - // Get dominators - while (remaining.Count > 0) - { - var block = remaining.Pop(); - - if (block == graph.EntryBlock) - continue; - - tempDoms.Clear(); - - if (block.Predecessors.Count != 0) - { - foreach (var predecessor in Dominators[block.Predecessors[0]]) - tempDoms.Add(predecessor); - - for (var i = 1; i < block.Predecessors.Count; i++) - tempDoms.IntersectWith(Dominators[block.Predecessors[i]]); - } + // Blocks not reachable from entry get null idom + foreach (var block in graph.Blocks) + ImmediateDominators[block] = null; - tempDoms.Add(block); + ImmediateDominators[entry] = entry; - // Given that all dominators can be at most the intersection of their predecessor dominators, - // there is no case in which an entirely new dominator gets added to a dominator set. - // this means that we do not have to compare all dominators by value; rather, - // we can just compare if the amount of dominators is the same, as the only way for that - // to be possible is for the same dominators to be in both sets. + // 2. Iterative Cooper-Harvey-Kennedy algorithm + var rpo = new List(postOrder); + rpo.Reverse(); // Reverse Post-Order: entry is first - if (tempDoms.Count != Dominators[block].Count) + Block Intersect(Block b1, Block b2) + { + var finger1 = b1; + var finger2 = b2; + while (finger1 != finger2) { - (Dominators[block], tempDoms) = (tempDoms, Dominators[block]); - - foreach (var successor in block.Successors) + while (postOrderIndex.TryGetValue(finger1, out var idx1) && + postOrderIndex.TryGetValue(finger2, out var idx2) && + idx1 < idx2) { - remaining.Push(successor); + finger1 = ImmediateDominators[finger1]!; + } + while (postOrderIndex.TryGetValue(finger1, out var idx1) && + postOrderIndex.TryGetValue(finger2, out var idx2) && + idx2 < idx1) + { + finger2 = ImmediateDominators[finger2]!; } } + return finger1; } - } - private void CalculatePostDominators(ISILControlFlowGraph graph) - { - PostDominators.Clear(); - - foreach (var block in graph.Blocks) - { - if (block == graph.ExitBlock) - PostDominators[block] = [block]; - else - PostDominators[block] = new HashSet(graph.Blocks); - } - - var remaining = new Stack(((IEnumerable)graph.Blocks).Reverse()); - - while (remaining.Count > 0) + var changed = true; + while (changed) { - var block = remaining.Pop(); - - if (block.Successors.Count == 0 && block != graph.ExitBlock) - continue; + changed = false; + foreach (var b in rpo) + { + if (b == entry) + continue; - var tempPostDoms = block.Successors.Count == 0 - ? new HashSet() - : new HashSet(PostDominators[block.Successors[0]]); + // Find first processed predecessor + Block? newIdom = null; + foreach (var p in b.Predecessors) + { + if (ImmediateDominators.TryGetValue(p, out var pIdom) && pIdom != null) + { + newIdom = p; + break; + } + } - for (var i = 1; i < block.Successors.Count; i++) - tempPostDoms.IntersectWith(PostDominators[block.Successors[i]]); + if (newIdom == null) + continue; - tempPostDoms.Add(block); + foreach (var p in b.Predecessors) + { + if (p != newIdom && ImmediateDominators.TryGetValue(p, out var pIdom) && pIdom != null) + { + newIdom = Intersect(p, newIdom); + } + } - if (!tempPostDoms.SetEquals(PostDominators[block])) - { - PostDominators[block] = tempPostDoms; - foreach (var predecessor in block.Predecessors) - remaining.Push(predecessor); + if (ImmediateDominators[b] != newIdom) + { + ImmediateDominators[b] = newIdom; + changed = true; + } } } + + // For entry block, convention is null (no strict dominator) + ImmediateDominators[entry] = null; } private void CalculateDominanceFrontiers(ISILControlFlowGraph graph) @@ -177,54 +200,12 @@ private void CalculateDominanceFrontiers(ISILControlFlowGraph graph) { var runner = predecessor; - while (runner != ImmediateDominators[block] && runner != null) + while (runner != null && runner != ImmediateDominators[block]) { DominanceFrontier[runner].Add(block); - runner = ImmediateDominators[runner]; + runner = ImmediateDominators.TryGetValue(runner, out var rIdom) ? rIdom : null; } } } } - - private void CalculateImmediatePostDominators(ISILControlFlowGraph graph) - { - foreach (var block in graph.Blocks) - ImmediatePostDominators[block] = ClosestStrictDominator(block, PostDominators); - } - - private void CalculateImmediateDominators(ISILControlFlowGraph graph) - { - foreach (var block in graph.Blocks) - ImmediateDominators[block] = ClosestStrictDominator(block, Dominators); - } - - /// - /// Returns the (post-)dominator of closest to it, i.e. its immediate - /// (post-)dominator. The strict (post-)dominators of a block form a chain under the domination - /// relation, so the closest one is simply the one with the largest (post-)dominator set. - /// Returns null for the root (entry/exit) or any block with no strict (post-)dominators. - /// - private static Block? ClosestStrictDominator(Block block, Dictionary> dominators) - { - if (!dominators.TryGetValue(block, out var doms)) - return null; - - Block? closest = null; - var closestCount = -1; - - foreach (var candidate in doms) - { - if (candidate == block) - continue; - - var count = dominators[candidate].Count; - if (count > closestCount) - { - closestCount = count; - closest = candidate; - } - } - - return closest; - } } diff --git a/Cpp2IL.Core/Il2CppApiFunctions/NewArm64KeyFunctionAddresses.cs b/Cpp2IL.Core/Il2CppApiFunctions/NewArm64KeyFunctionAddresses.cs index 28bf3a2a8..fb3af9e69 100644 --- a/Cpp2IL.Core/Il2CppApiFunctions/NewArm64KeyFunctionAddresses.cs +++ b/Cpp2IL.Core/Il2CppApiFunctions/NewArm64KeyFunctionAddresses.cs @@ -1,6 +1,8 @@ +using System; using System.Collections.Generic; using System.Linq; using Disarm; +using Disarm.InternalDisassembly; using Cpp2IL.Core.Logging; using Cpp2IL.Core.Utils; @@ -8,6 +10,15 @@ namespace Cpp2IL.Core.Il2CppApiFunctions; public class NewArm64KeyFunctionAddresses : BaseKeyFunctionAddresses { + private static readonly (string Namespace, string Type, string Method)[] WriteBarrierAnchors = + [ + ("System.Threading.Tasks", "Task`1", "GetAwaiter"), + ("System.Threading.Tasks", "Task", "GetAwaiter"), + ("System.Threading", "ExecutionContext", "get_LogicalCallContext"), + ("System.Threading", "CancellationTokenSource", "get_Token"), + ("System", "BadImageFormatException", "get_Message"), + ]; + private List? _cachedDisassembledBytes; private List DisassembleTextSection() @@ -137,4 +148,84 @@ protected override int GetCallerCount(ulong toWhere) //Find all jumps to the target address return disassembly.Count(i => i.Mnemonic is Arm64Mnemonic.B or Arm64Mnemonic.BL && i.BranchTarget == toWhere); } + + protected override ulong GetWriteBarrier() + { + Logger.Verbose("\tLooking for Il2CppCodeGenWriteBarrier via corlib reference-field stores..."); + + var votes = new Dictionary(); + + foreach (var (@namespace, typeName, methodName) in WriteBarrierAnchors) + { + var method = ReflectionCache.GetType(typeName, @namespace)?.Methods?.FirstOrDefault(m => m.Name == methodName); + + if (method == null || method.MethodPointer == 0) + continue; + + var body = NewArm64Utils.GetArm64MethodBodyAtVirtualAddress(_appContext, method.MethodPointer, true); + + foreach (var target in FindWriteBarrierCalls(body).Distinct()) + votes[target] = (votes.TryGetValue(target, out var count) ? count : 0) + 1; + } + + var best = 0ul; + var bestVotes = 0; + + foreach (var vote in votes) + { + if (vote.Value <= bestVotes) + continue; + + best = vote.Key; + bestVotes = vote.Value; + } + + if (best == 0) + { + Logger.VerboseNewline("Not found. Write barriers disabled?"); + return 0; + } + + Logger.VerboseNewline($"Found at 0x{best:X} (found in {bestVotes} of {WriteBarrierAnchors.Length} checked methods)"); + + return best; + } + + private static IEnumerable FindWriteBarrierCalls(List body) + { + const int window = 6; + for (var i = 0; i < body.Count; i++) + { + if (body[i].Mnemonic != Arm64Mnemonic.BL) + continue; + + if (IsPrecededByGuardedStore(body, i, window)) + yield return body[i].BranchTarget; + } + } + + private static bool IsPrecededByGuardedStore(List body, int callIndex, int window) + { + var start = Math.Max(0, callIndex - window); + for (var i = start; i < callIndex; i++) + { + var add = body[i]; + if (add.Mnemonic == Arm64Mnemonic.ADD && add.Op0Reg == Arm64Register.X0 && add.Op2Kind == Arm64OperandKind.Immediate) + { + var baseReg = add.Op1Reg; + var offset = add.Op2Imm; + for (var j = start; j < callIndex; j++) + { + var store = body[j]; + if (store.Mnemonic is Arm64Mnemonic.STR or Arm64Mnemonic.STUR + && store.MemBase == baseReg && store.MemOffset == offset) + return true; + if (store.Mnemonic == Arm64Mnemonic.STP + && (store.MemBase == baseReg || baseReg == Arm64Register.X31 && store.MemBase == Arm64Register.X31)) + return true; + } + } + } + return false; + } } diff --git a/Cpp2IL.Core/IlGenerator.cs b/Cpp2IL.Core/IlGenerator.cs index 85620388a..3545c2793 100644 --- a/Cpp2IL.Core/IlGenerator.cs +++ b/Cpp2IL.Core/IlGenerator.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -5,9 +6,11 @@ using AsmResolver.DotNet.Code.Cil; using AsmResolver.DotNet.Signatures; using AsmResolver.PE.DotNet.Cil; +using Cpp2IL.Core.Analysis; using Cpp2IL.Core.Graphs; using Cpp2IL.Core.ISIL; using Cpp2IL.Core.Model.Contexts; +using Cpp2IL.Core.Utils; using Cpp2IL.Core.Utils.AsmResolver; namespace Cpp2IL.Core; @@ -66,38 +69,61 @@ public static void GenerateIl(MethodAnalysisContext context, MethodDefinition de definition.CilMethodBody = body; - // Make sure context.Locals actually has all locals (idk why it doesn't sometimes) - foreach (var operand in context.ControlFlowGraph.Instructions.SelectMany(i => i.Operands)) + // Make sure context.Locals actually has all locals across all blocks and operands + var allLocals = new HashSet(context.Locals); + foreach (var block in context.ControlFlowGraph.Blocks) { - LocalVariable? local = null; - - if (operand is FieldReference field) - local = field.Local; - - if (operand is LocalVariable local2) - local = local2; - - if (operand is MemoryOperand memory && memory.Base is LocalVariable local3) - local = local3; - - var elementOperand = operand is AddressOf { Target: ArrayAccess elementAddress } ? elementAddress : operand; - - if (elementOperand is ArrayAccess arrayAccess) + foreach (var instruction in block.Instructions) { - local = arrayAccess.Array; - - if (arrayAccess.Index is LocalVariable index && !context.Locals.Contains(index)) - context.Locals.Add(index); + foreach (var operand in instruction.Operands) + { + CollectLocals(operand, allLocals); + } } + } + context.Locals = allLocals.ToList(); - if (operand is ArrayLength arrayLength) - local = arrayLength.Array; - - if (operand is AddressOf { Target: LocalVariable addressed }) - local = addressed; + // Infer any remaining untyped locals from instructions that assign to them + foreach (var local in context.Locals) + { + if (local.Type != null) continue; - if (local != null && !context.Locals.Contains(local)) - context.Locals.Add(local); + foreach (var inst in context.ControlFlowGraph!.Instructions) + { + if (inst.Operands.Count > 0 && ReferenceEquals(inst.Operands[0], local)) + { + if (inst.OpCode is >= OpCode.CheckEqual and <= OpCode.CheckLessOrEqual) + { + local.Type = context.AppContext.SystemTypes.SystemBooleanType; + break; + } + if (inst.OpCode is OpCode.And or OpCode.Or or OpCode.Xor or OpCode.ShiftLeft or OpCode.ShiftRight or OpCode.Modulo) + { + local.Type = context.AppContext.SystemTypes.SystemInt32Type; + break; + } + if (inst.OpCode is OpCode.Add or OpCode.Subtract or OpCode.Multiply or OpCode.Divide) + { + local.Type = context.AppContext.SystemTypes.SystemInt32Type; + break; + } + if (inst.OpCode == OpCode.Call && inst.Operands[0] is MethodAnalysisContext callee && !callee.IsVoid) + { + local.Type = callee.ReturnType; + break; + } + if (inst.OpCode == OpCode.Newobj && inst.Operands.Count > 1 && inst.Operands[1] is TypeAnalysisContext allocType) + { + local.Type = allocType; + break; + } + if (inst.OpCode == OpCode.NewArr && inst.Operands.Count > 1 && inst.Operands[1] is SzArrayTypeAnalysisContext arrType) + { + local.Type = arrType; + break; + } + } + } } // Map ISIL locals to IL @@ -130,11 +156,19 @@ public static void GenerateIl(MethodAnalysisContext context, MethodDefinition de Dictionary blockEntryMap = []; List<(CilInstruction BranchInstruction, Block TargetBlock)> pendingBlockBranchFixups = []; - foreach (var block in context.ControlFlowGraph!.Blocks) + var entrySuccessor = context.ControlFlowGraph!.EntryBlock.Successors.FirstOrDefault(s => s != context.ControlFlowGraph.ExitBlock); + var orderedBlocks = new List(); + if (entrySuccessor != null && context.ControlFlowGraph.Blocks.Contains(entrySuccessor)) + orderedBlocks.Add(entrySuccessor); + + foreach (var b in context.ControlFlowGraph.Blocks) { - if (block == context.ControlFlowGraph.EntryBlock || block == context.ControlFlowGraph.ExitBlock) - continue; + if (b != context.ControlFlowGraph.EntryBlock && b != context.ControlFlowGraph.ExitBlock && !orderedBlocks.Contains(b)) + orderedBlocks.Add(b); + } + foreach (var block in orderedBlocks) + { if (block.Instructions.Count == 0) continue; @@ -214,13 +248,44 @@ public static void GenerateIl(MethodAnalysisContext context, MethodDefinition de branchInstruction.Operand = new CilInstructionLabel(target); } - // Add analysis warnings var instructions = body.Instructions; + + // Peephole pass: eliminate redundant branch-to-next-instruction + for (var i = 0; i < instructions.Count - 1; i++) + { + var cur = instructions[i]; + if (cur.OpCode.Code is CilCode.Br or CilCode.Br_S) + { + var next = instructions[i + 1]; + if (cur.Operand is CilInstructionLabel lbl && lbl.Instruction == next) + { + cur.OpCode = CilOpCodes.Nop; + cur.Operand = null; + } + } + } + + // Add analysis warnings foreach (var warning in context.AnalysisWarnings) { instructions.Add(CilOpCodes.Ldstr, Diagnostic("Warning: " + warning)); instructions.Add(CilOpCodes.Call, writeLine); } + + // Ensure method body always ends with a valid terminator instruction + if (instructions.Count == 0 || !IsTerminator(instructions[^1])) + { + if (!context.IsVoid) + PushDefaultOf(context.ReturnType, definition, instructions); + instructions.Add(CilOpCodes.Ret); + } + } + + private static bool IsTerminator(CilInstruction instruction) + { + var code = instruction.OpCode.Code; + return code is CilCode.Ret or CilCode.Throw or CilCode.Rethrow + or CilCode.Br or CilCode.Br_S or CilCode.Leave or CilCode.Leave_S; } // Limit so we don't run into the 16mb limit (see AsmResolver issue #775) @@ -309,8 +374,22 @@ private static List GenerateInstructions(Instruction instruction break; } - LoadOperand(instruction.Operands[1], method, locals, writeLine, DestinationType(instruction.Operands[0])); - StoreToOperand(instruction.Operands[0], method, locals, writeLine); + if (instruction.Operands[0] is MemoryOperand memTarget && memTarget.Base is LocalVariable { Type: SzArrayTypeAnalysisContext memArrType } memArrLocal && memTarget.Addend >= 0x20) + { + var elemType = memArrType.ElementType; + var elemSize = elemType.IsValueType ? Math.Max(1, (int)TypeSizes.UnboxedSize(elemType, context.AppContext.Binary.PointerSizeBytes)) : context.AppContext.Binary.PointerSizeBytes; + var elemIdx = (int)((memTarget.Addend - 0x20) / elemSize); + LoadLocal(memArrLocal, method, locals); + instructions.Add(CilOpCodes.Ldc_I4, elemIdx); + LoadOperand(instruction.Operands[1], method, locals, writeLine, elemType); + instructions.Add(CilOpCodes.Stelem, elemType.ToTypeSignature().ToTypeDefOrRef()); + break; + } + + var destType = DestinationType(instruction.Operands[0], context.AppContext); + LoadOperand(instruction.Operands[1], method, locals, writeLine, destType); + var srcType = (instruction.Operands[1] as LocalVariable)?.Type ?? (instruction.Operands[1] as FieldReference)?.Field.FieldType; + StoreToOperand(instruction.Operands[0], method, locals, writeLine, srcType); break; case OpCode.NewArr: @@ -383,19 +462,115 @@ private static List GenerateInstructions(Instruction instruction case OpCode.Phi: instructions.Add(CilOpCodes.Ldstr, Diagnostic($"Phi opcodes should not exist at this point in decompilation ({instruction})")); instructions.Add(CilOpCodes.Call, writeLine); + if (instruction.Operands.Count > 0 && instruction.Operands[0] is LocalVariable phiDest) + { + if (instruction.Operands.Count > 1) + LoadOperand(instruction.Operands[1], method, locals, writeLine); + else + PushDefaultOf(phiDest.Type ?? context.AppContext.SystemTypes.SystemObjectType, method, instructions); + StoreToOperand(phiDest, method, locals, writeLine); + } break; case OpCode.Call: case OpCode.CallVoid: - if (instruction.Operands[0] is not MethodAnalysisContext targetMethod) + MethodAnalysisContext? targetMethod = instruction.Operands[0] as MethodAnalysisContext; + if (targetMethod == null) + { + if (instruction.Operands[0] is Immediate targetAddress) + { + var resolvedTarget = MetadataResolver.FollowBranchTrampolines(context.AppContext, targetAddress.UnsignedValue); + if (context.AppContext.MethodsByAddress.TryGetValue(resolvedTarget, out var methods) && methods.Count > 0) + { + targetMethod = methods[0]; + } + else if (context.AppContext.Binary.ConcreteGenericImplementationsByAddress.TryGetValue(resolvedTarget, out var genericRefs) && genericRefs.Count > 0) + { + targetMethod = context.AppContext.ResolveContextForMethod(genericRefs[0].BaseMethod); + } + } + } + + if (targetMethod == null) { if (instruction.Operands[0] is Immediate targetAddress) + { instructions.Add(CilOpCodes.Ldstr, $"Method not found @{targetAddress.UnsignedValue:X}"); - else // Probably key function. Just the target, the full operand dump is huge and blows the 16MB #US heap limit + instructions.Add(CilOpCodes.Call, writeLine); + if (instruction.OpCode == OpCode.Call && instruction.Operands.Count > 1 && instruction.Operands[1] is LocalVariable retLocal) + { + PushDefaultOf(retLocal.Type ?? context.AppContext.SystemTypes.SystemObjectType, method, instructions); + StoreToOperand(retLocal, method, locals, writeLine); + } + break; + } + else if (instruction.Operands[0] is StringLiteral { Value: var kfName }) + { + if (kfName is "SzArrayNew" or "il2cpp_vm_array_new_specific" or "il2cpp_array_new_specific") + { + if (instruction.Operands.Count > 1 && instruction.Operands[1] is LocalVariable arrResult) + { + if (arrResult.Type is SzArrayTypeAnalysisContext szArr) + { + if (instruction.Operands.Count > 3) + LoadOperand(instruction.Operands[3], method, locals, writeLine); + else + instructions.Add(CilOpCodes.Ldc_I4_0); + instructions.Add(CilOpCodes.Newarr, szArr.ElementType.ToTypeSignature().ToTypeDefOrRef()); + } + else + { + PushDefaultOf(arrResult.Type ?? context.AppContext.SystemTypes.SystemObjectType, method, instructions); + } + StoreToOperand(arrResult, method, locals, writeLine); + } + break; + } + + if (kfName == "il2cpp_vm_object_box") + { + if (instruction.Operands.Count > 1 && instruction.Operands[1] is LocalVariable boxResult) + { + if (instruction.Operands.Count > 3 && instruction.Operands[2] is TypeAnalysisContext targetBoxedType) + { + LoadOperand(instruction.Operands[3], method, locals, writeLine, targetBoxedType); + instructions.Add(CilOpCodes.Box, targetBoxedType.ToTypeSignature().ToTypeDefOrRef()); + } + else + { + PushDefaultOf(boxResult.Type ?? context.AppContext.SystemTypes.SystemObjectType, method, instructions); + } + StoreToOperand(boxResult, method, locals, writeLine); + } + break; + } + + // For other key functions or class_init, cleanly initialize return value if any + if (instruction.OpCode == OpCode.Call && instruction.Operands.Count > 1 && instruction.Operands[1] is LocalVariable retLocal) + { + if (context.ControlFlowGraph!.Instructions.Any(i => i != instruction && i.Operands.Contains(retLocal))) + { + PushDefaultOf(retLocal.Type ?? context.AppContext.SystemTypes.SystemObjectType, method, instructions); + StoreToOperand(retLocal, method, locals, writeLine); + } + } + break; + } + else + { instructions.Add(CilOpCodes.Ldstr, Diagnostic($"Unknown call target operand: {instruction.Operands[0]}")); - - instructions.Add(CilOpCodes.Call, writeLine); - break; + instructions.Add(CilOpCodes.Call, writeLine); + // Any remaining unknown target operand: safely provide default return value + if (instruction.OpCode == OpCode.Call && instruction.Operands.Count > 1 && instruction.Operands[1] is LocalVariable retLocal) + { + if (context.ControlFlowGraph!.Instructions.Any(i => i != instruction && i.Operands.Contains(retLocal))) + { + PushDefaultOf(retLocal.Type ?? context.AppContext.SystemTypes.SystemObjectType, method, instructions); + StoreToOperand(retLocal, method, locals, writeLine); + } + } + break; + } } var importedMethod = targetMethod.ToMethodDescriptor(); @@ -427,7 +602,7 @@ private static List GenerateInstructions(Instruction instruction if (i < availableArgs) LoadOperand(instruction.Operands[callParamIndex + i], method, locals, writeLine, parameterType); else - PushDefaultOf(parameterType, instructions); + PushDefaultOf(parameterType, method, instructions); } instructions.Add(CilOpCodes.Call, importedMethod); @@ -437,7 +612,7 @@ private static List GenerateInstructions(Instruction instruction if (!targetMethod.IsVoid) { if (instruction.OpCode == OpCode.Call) - StoreToOperand(instruction.Operands[1], method, locals, writeLine); + StoreToOperand(instruction.Operands[1], method, locals, writeLine, targetMethod.ReturnType); else instructions.Add(CilOpCodes.Pop); } @@ -447,6 +622,11 @@ private static List GenerateInstructions(Instruction instruction case OpCode.IndirectCall: instructions.Add(CilOpCodes.Ldstr, Diagnostic($"Indirect call: {instruction.Operands[0]} (should have been resolved before IL gen)")); instructions.Add(CilOpCodes.Call, writeLine); + if (instruction.Operands.Count > 1 && instruction.Operands[1] is LocalVariable indirectRet) + { + PushDefaultOf(indirectRet.Type ?? context.AppContext.SystemTypes.SystemObjectType, method, instructions); + StoreToOperand(indirectRet, method, locals, writeLine); + } break; case OpCode.Return: @@ -455,7 +635,7 @@ private static List GenerateInstructions(Instruction instruction if (instruction.Operands.Count == 1) LoadOperand(instruction.Operands[0], method, locals, writeLine, context.ReturnType); else - instructions.Add(CilOpCodes.Ldnull); // ret still pops a value even if we lost track of it + PushDefaultOf(context.ReturnType, method, instructions); } instructions.Add(CilOpCodes.Ret); break; @@ -472,6 +652,9 @@ private static List GenerateInstructions(Instruction instruction case OpCode.IndirectJump: instructions.Add(CilOpCodes.Ldstr, Diagnostic($"Indirect jump: {instruction.Operands[0]} (should have been resolved before IL gen)")); instructions.Add(CilOpCodes.Call, writeLine); + if (!context.IsVoid) + PushDefaultOf(context.ReturnType, method, instructions); + instructions.Add(CilOpCodes.Ret); break; case OpCode.ShiftStack: @@ -506,11 +689,27 @@ private static List GenerateInstructions(Instruction instruction // Float arithmetic on a promoted integer operand needs an explicit conversion, so both // operands are coerced to the (float) result type. A no-op when they already match. var floatConversion = FloatArithmeticConversion(instruction); + var isNumericOp = instruction.OpCode is OpCode.Add or OpCode.Subtract or OpCode.Multiply + or OpCode.Divide or OpCode.Modulo or OpCode.ShiftLeft or OpCode.ShiftRight + or OpCode.And or OpCode.Or or OpCode.Xor; - LoadOperand(instruction.Operands[1], method, locals, writeLine); + var isComparison = instruction.OpCode is >= OpCode.CheckEqual and <= OpCode.CheckLessOrEqual; + var operandType = DestinationType(instruction.Operands[0], context.AppContext); + if (isNumericOp && (operandType == null || !operandType.IsValueType)) + operandType = context.AppContext.SystemTypes.SystemInt32Type; + + if (isComparison) + { + operandType = (instruction.Operands[1] as LocalVariable)?.Type + ?? (instruction.Operands[1] as FieldReference)?.Field.FieldType + ?? (instruction.Operands[2] as LocalVariable)?.Type + ?? (instruction.Operands[2] as FieldReference)?.Field.FieldType; + } + + LoadOperand(instruction.Operands[1], method, locals, writeLine, operandType); if (floatConversion is { } conv1) instructions.Add(conv1); - LoadOperand(instruction.Operands[2], method, locals, writeLine); + LoadOperand(instruction.Operands[2], method, locals, writeLine, operandType); if (floatConversion is { } conv2) instructions.Add(conv2); @@ -553,16 +752,20 @@ private static List GenerateInstructions(Instruction instruction case OpCode.Xor: instructions.Add(CilOpCodes.Xor); break; } - StoreToOperand(instruction.Operands[0], method, locals, writeLine); + var resType = isComparison ? context.AppContext.SystemTypes.SystemBooleanType : operandType; + StoreToOperand(instruction.Operands[0], method, locals, writeLine, resType); break; case OpCode.Not: case OpCode.Negate: - LoadOperand(instruction.Operands[1], method, locals, writeLine); + var isBool = IsBoolean(instruction.Operands[1], context) + || (instruction.Operands[0] is LocalVariable destLoc && destLoc.Type == context.AppContext.SystemTypes.SystemBooleanType); + + LoadOperand(instruction.Operands[1], method, locals, writeLine, isBool ? context.AppContext.SystemTypes.SystemBooleanType : null); if (instruction.OpCode == OpCode.Negate) instructions.Add(CilOpCodes.Neg); - else if (IsBoolean(instruction.Operands[1], context)) + else if (isBool) { instructions.Add(CilOpCodes.Ldc_I4_0); instructions.Add(CilOpCodes.Ceq); @@ -570,7 +773,8 @@ private static List GenerateInstructions(Instruction instruction else instructions.Add(CilOpCodes.Not); - StoreToOperand(instruction.Operands[0], method, locals, writeLine); + var notType = isBool ? context.AppContext.SystemTypes.SystemBooleanType : DestinationType(instruction.Operands[0], context.AppContext); + StoreToOperand(instruction.Operands[0], method, locals, writeLine, notType); break; default: @@ -644,10 +848,33 @@ private static void LoadOperand(IOperand operand, MethodDefinition method, switch (operand) { case Immediate { Value: >= int.MinValue and <= int.MaxValue } immediate: - instructions.Add(CilOpCodes.Ldc_I4, (int)immediate.Value); + if (expectedType?.FullName == "System.Single") + instructions.Add(CilOpCodes.Ldc_R4, (float)immediate.Value); + else if (expectedType?.FullName == "System.Double") + instructions.Add(CilOpCodes.Ldc_R8, (double)immediate.Value); + else if (expectedType?.FullName is "System.Int64" or "System.UInt64") + instructions.Add(CilOpCodes.Ldc_I8, immediate.Value); + else + { + instructions.Add(CilOpCodes.Ldc_I4, (int)immediate.Value); + if (expectedType?.FullName is "System.IntPtr" or "System.UIntPtr") + instructions.Add(CilOpCodes.Conv_I); + } break; case Immediate immediate: - instructions.Add(CilOpCodes.Ldc_I8, immediate.Value); + if (expectedType?.FullName == "System.Double") + instructions.Add(CilOpCodes.Ldc_R8, (double)immediate.Value); + else if (expectedType?.FullName is "System.Int32" or "System.UInt32" or "System.Boolean") + { + instructions.Add(CilOpCodes.Ldc_I8, immediate.Value); + instructions.Add(CilOpCodes.Conv_I4); + } + else + { + instructions.Add(CilOpCodes.Ldc_I8, immediate.Value); + if (expectedType?.FullName is "System.IntPtr" or "System.UIntPtr") + instructions.Add(CilOpCodes.Conv_I); + } break; case FloatLiteral f: instructions.Add(CilOpCodes.Ldc_R4, f.Value); @@ -656,10 +883,34 @@ private static void LoadOperand(IOperand operand, MethodDefinition method, instructions.Add(CilOpCodes.Ldc_R8, d.Value); break; case StringLiteral s: - instructions.Add(CilOpCodes.Ldstr, s.Value); + if (expectedType != null && expectedType.IsValueType) + PushDefaultOf(expectedType, method, instructions); + else + instructions.Add(CilOpCodes.Ldstr, s.Value); break; case LocalVariable local: LoadLocal(local, method, locals); + if (expectedType != null) + { + if (expectedType.FullName == "System.Object" && local.Type is { IsValueType: true } valType) + { + instructions.Add(CilOpCodes.Box, valType.ToTypeSignature().ToTypeDefOrRef()); + } + else if (expectedType.IsValueType && local.Type is { IsValueType: false } and not null) + { + instructions.Add(CilOpCodes.Unbox_Any, expectedType.ToTypeSignature().ToTypeDefOrRef()); + } + else if (expectedType.FullName is "System.IntPtr" or "System.UIntPtr" + && local.Type?.FullName is "System.Int32" or "System.UInt32") + { + instructions.Add(CilOpCodes.Conv_I); + } + else if (expectedType.FullName is "System.Int32" or "System.UInt32" + && local.Type?.FullName is "System.IntPtr" or "System.UIntPtr" or "System.Int64" or "System.UInt64") + { + instructions.Add(CilOpCodes.Conv_I4); + } + } break; case ArrayLength arrayLength: LoadLocal(arrayLength.Array, method, locals); @@ -667,7 +918,7 @@ private static void LoadOperand(IOperand operand, MethodDefinition method, instructions.Add(CilOpCodes.Conv_I4); break; case AddressOf { Target: LocalVariable addressed }: - instructions.Add(CilOpCodes.Ldloca, locals[addressed]); + instructions.Add(CilOpCodes.Ldloca, GetOrCreateLocal(addressed, method, locals)); break; case AddressOf { Target: ArrayAccess elementAddress }: LoadLocal(elementAddress.Array, method, locals); @@ -704,10 +955,91 @@ private static void LoadOperand(IOperand operand, MethodDefinition method, : new CilInstruction(CilOpCodes.Ldind_Ref)); break; } + + // String properties: Length and char indexer + if (memory.Base is LocalVariable { Type.FullName: "System.String" } strLocal) + { + if (memory.Index == null && memory.Addend == 0x10) + { + var getLength = module.CorLibTypeFactory.CorLibScope + .CreateTypeReference("System", "String") + .CreateMemberReference("get_Length", MethodSignature.CreateInstance(module.CorLibTypeFactory.Int32)); + LoadLocal(strLocal, method, locals); + instructions.Add(CilOpCodes.Callvirt, getLength); + break; + } + if (memory.Addend == 0x14 && memory.Index != null) + { + var getChars = module.CorLibTypeFactory.CorLibScope + .CreateTypeReference("System", "String") + .CreateMemberReference("get_Chars", MethodSignature.CreateInstance(module.CorLibTypeFactory.Char, [module.CorLibTypeFactory.Int32])); + LoadLocal(strLocal, method, locals); + LoadOperand(memory.Index, method, locals, writeLine); + instructions.Add(CilOpCodes.Callvirt, getChars); + break; + } + } + + // Array: Length and element access + if (memory.Base is LocalVariable { Type: SzArrayTypeAnalysisContext arrType } arrLocal) + { + if (memory.Index == null && memory.Addend == 0x18) + { + LoadLocal(arrLocal, method, locals); + instructions.Add(CilOpCodes.Ldlen); + instructions.Add(CilOpCodes.Conv_I4); + break; + } + if (memory.Index != null) + { + LoadLocal(arrLocal, method, locals); + LoadOperand(memory.Index, method, locals, writeLine); + instructions.Add(CilOpCodes.Ldelem, arrType.ElementType.ToTypeSignature().ToTypeDefOrRef()); + break; + } + } + + // Cleanly handle internal runtime metadata structures (RGCTX tables, Il2CppClass tables, static field storage) + if (memory.Base is LocalVariable baseLocal && (baseLocal.Type is RgctxTableTypeAnalysisContext or MethodRgctxTableTypeAnalysisContext + or RuntimeClassTypeAnalysisContext or StaticFieldStorageTypeAnalysisContext + || baseLocal.Type?.FullName?.Contains("Il2CppRgctx") == true || baseLocal.Type?.FullName?.Contains("Il2CppClass") == true + || memory.Addend is 0xB8 or 0x130 or 0x135 or 0x138)) + { + if (expectedType != null) + PushDefaultOf(expectedType, method, instructions); + else + { + instructions.Add(CilOpCodes.Ldc_I4_0); + instructions.Add(CilOpCodes.Conv_I); + } + break; + } + + // Cleanly handle absolute uninitialized metadata slots or data globals (memory.Base == null) + if (memory.Base == null) + { + if (expectedType != null) + PushDefaultOf(expectedType, method, instructions); + else + instructions.Add(CilOpCodes.Ldnull); + break; + } + instructions.Add(CilOpCodes.Ldstr, Diagnostic("Unmanaged memory load: " + operand)); instructions.Add(CilOpCodes.Call, writeLine); - instructions.Add(CilOpCodes.Ldc_I4_0); - instructions.Add(CilOpCodes.Conv_I); + if (expectedType != null) + { + PushDefaultOf(expectedType, method, instructions); + } + else if (memory.Base is LocalVariable lv && lv.Type != null && !lv.Type.IsValueType) + { + instructions.Add(CilOpCodes.Ldnull); + } + else + { + instructions.Add(CilOpCodes.Ldc_I4_0); + instructions.Add(CilOpCodes.Conv_I); + } break; case RuntimeMethodInfoAnalysisContext runtimeMethod: // A delegate constructor takes its target as a native pointer, which is exactly ldftn. @@ -718,8 +1050,13 @@ private static void LoadOperand(IOperand operand, MethodDefinition method, } //Not fully implemented, these basically shouldn't actually ever exist in the final IL. - instructions.Add(CilOpCodes.Ldc_I4_0); - instructions.Add(CilOpCodes.Conv_I); + if (expectedType != null) + PushDefaultOf(expectedType, method, instructions); + else + { + instructions.Add(CilOpCodes.Ldc_I4_0); + instructions.Add(CilOpCodes.Conv_I); + } break; case RuntimeFieldInfoAnalysisContext runtimeField: // fieldof(F), e.g. the handle InitializeArray takes. @@ -729,13 +1066,23 @@ private static void LoadOperand(IOperand operand, MethodDefinition method, break; } - instructions.Add(CilOpCodes.Ldc_I4_0); - instructions.Add(CilOpCodes.Conv_I); + if (expectedType != null) + PushDefaultOf(expectedType, method, instructions); + else + { + instructions.Add(CilOpCodes.Ldc_I4_0); + instructions.Add(CilOpCodes.Conv_I); + } break; case RuntimeClassTypeAnalysisContext or RgctxTableTypeAnalysisContext or MethodRgctxTableTypeAnalysisContext or StaticFieldStorageTypeAnalysisContext: - instructions.Add(CilOpCodes.Ldc_I4_0); - instructions.Add(CilOpCodes.Conv_I); + if (expectedType != null) + PushDefaultOf(expectedType, method, instructions); + else + { + instructions.Add(CilOpCodes.Ldc_I4_0); + instructions.Add(CilOpCodes.Conv_I); + } break; case TypeAnalysisContext type: //typeof(T) @@ -752,7 +1099,10 @@ private static void LoadOperand(IOperand operand, MethodDefinition method, default: instructions.Add(CilOpCodes.Ldstr, Diagnostic("Unknown operand: " + operand)); instructions.Add(CilOpCodes.Call, writeLine); - instructions.Add(CilOpCodes.Ldnull); + if (expectedType != null) + PushDefaultOf(expectedType, method, instructions); + else + instructions.Add(CilOpCodes.Ldnull); break; } } @@ -808,39 +1158,120 @@ private static bool IsKlassPointerLoad(IOperand operand, out LocalVariable local return false; } - private static void PushDefaultOf(TypeAnalysisContext type, CilInstructionCollection instructions) + private static void PushDefaultOf(TypeAnalysisContext? type, MethodDefinition method, CilInstructionCollection instructions) { - //TODO Remove this, we should be handling arguments correctly in ISIL resolution, this is a hack to emit balanced stacks. - //TODO At the *very* least we should emit a console.writeline saying that we did this. - if (!type.IsValueType) + if (type == null) { instructions.Add(CilOpCodes.Ldnull); return; } - switch (type.FullName) + if (type.FullName == "System.Single") { - case "System.Single": instructions.Add(CilOpCodes.Ldc_R4, 0f); break; - case "System.Double": instructions.Add(CilOpCodes.Ldc_R8, 0d); break; - case "System.Int64" or "System.UInt64": instructions.Add(CilOpCodes.Ldc_I8, 0L); break; - default: instructions.Add(CilOpCodes.Ldc_I4_0); break; + instructions.Add(CilOpCodes.Ldc_R4, 0f); + return; + } + if (type.FullName == "System.Double") + { + instructions.Add(CilOpCodes.Ldc_R8, 0d); + return; + } + if (type.FullName is "System.Int64" or "System.UInt64") + { + instructions.Add(CilOpCodes.Ldc_I8, 0L); + return; + } + if (type.FullName is "System.IntPtr" or "System.UIntPtr") + { + instructions.Add(CilOpCodes.Ldc_I4_0); + instructions.Add(CilOpCodes.Conv_I); + return; + } + if (type.FullName is "System.Boolean" or "System.Byte" or "System.SByte" + or "System.Int16" or "System.UInt16" or "System.Int32" or "System.UInt32" or "System.Char") + { + instructions.Add(CilOpCodes.Ldc_I4_0); + return; + } + + if (type.IsValueType || type is GenericParameterTypeAnalysisContext) + { + var typeSig = type.ToTypeSignature(); + var scratch = new CilLocalVariable(typeSig); + method.CilMethodBody!.LocalVariables.Add(scratch); + + instructions.Add(CilOpCodes.Ldloca, scratch); + instructions.Add(CilOpCodes.Initobj, typeSig.ToTypeDefOrRef()); + instructions.Add(CilOpCodes.Ldloc, scratch); + return; } + + instructions.Add(CilOpCodes.Ldnull); } private static bool IsBoolean(IOperand operand, MethodAnalysisContext context) => - operand is LocalVariable { Type: { } type } && type == context.AppContext.SystemTypes.SystemBooleanType; + (operand is LocalVariable { Type: { } type } && type == context.AppContext.SystemTypes.SystemBooleanType) + || (operand is FieldReference field && field.Field.FieldType == context.AppContext.SystemTypes.SystemBooleanType); private static bool IsZeroConstant(IOperand operand) => operand is Immediate { Value: 0 }; - private static TypeAnalysisContext? DestinationType(IOperand destination) => + private static TypeAnalysisContext? DestinationType(IOperand destination, ApplicationAnalysisContext? appContext = null) => destination switch { - LocalVariable local => local.Type, + LocalVariable local => local.Type ?? appContext?.SystemTypes.SystemObjectType, FieldReference field => field.Field.FieldType, ArrayAccess { Array.Type: SzArrayTypeAnalysisContext array } => array.ElementType, _ => null }; + private static void CollectLocals(IOperand? operand, HashSet set) + { + if (operand == null) return; + switch (operand) + { + case LocalVariable lv: + set.Add(lv); + break; + case FieldReference fr: + if (fr.Local != null) set.Add(fr.Local); + break; + case MemoryOperand mo: + CollectLocals(mo.Base, set); + CollectLocals(mo.Index, set); + break; + case ArrayAccess aa: + if (aa.Array != null) set.Add(aa.Array); + CollectLocals(aa.Index, set); + break; + case ArrayLength al: + if (al.Array != null) set.Add(al.Array); + break; + case AddressOf ao: + CollectLocals(ao.Target, set); + break; + case IEnumerable list: + foreach (var op in list) CollectLocals(op, set); + break; + } + } + + private static CilLocalVariable GetOrCreateLocal(LocalVariable local, MethodDefinition method, Dictionary locals) + { + if (locals.TryGetValue(local, out var ilLocal)) + return ilLocal; + + TypeSignature ilType; + if (local.Type != null && local.Type.FullName != "System.Void") + ilType = local.Type.ToTypeSignature(); + else + ilType = method.DeclaringModule!.CorLibTypeFactory.Object; + + ilLocal = new CilLocalVariable(ilType); + method.CilMethodBody!.LocalVariables.Add(ilLocal); + locals[local] = ilLocal; + return ilLocal; + } + private static void LoadLocal(LocalVariable local, MethodDefinition method, Dictionary locals) { var instructions = method.CilMethodBody!.Instructions; @@ -856,18 +1287,25 @@ private static void LoadLocal(LocalVariable local, MethodDefinition method, Dict if (parameter != null) instructions.Add(CilOpCodes.Ldarg, parameter); else - instructions.Add(CilOpCodes.Ldloc, locals[local]); + instructions.Add(CilOpCodes.Ldloc, GetOrCreateLocal(local, method, locals)); } private static void StoreToOperand(IOperand operand, MethodDefinition method, - Dictionary locals, IMethodDescriptor writeLine) + Dictionary locals, IMethodDescriptor writeLine, + TypeAnalysisContext? valueTypeOnStack = null) { var instructions = method.CilMethodBody!.Instructions; switch (operand) { case LocalVariable local: - instructions.Add(CilOpCodes.Stloc, locals[local]); + var targetLocal = GetOrCreateLocal(local, method, locals); + if (targetLocal.VariableType.FullName == "System.Object" + && valueTypeOnStack is { IsValueType: true } valType) + { + instructions.Add(CilOpCodes.Box, valType.ToTypeSignature().ToTypeDefOrRef()); + } + instructions.Add(CilOpCodes.Stloc, targetLocal); break; case FieldReference field: @@ -904,11 +1342,25 @@ private static void StoreToOperand(IOperand operand, MethodDefinition method, break; case MemoryOperand memory: + if (memory.Base is LocalVariable memArrLocal && memArrLocal.Type is SzArrayTypeAnalysisContext memArrType && memory.Addend >= 0x20) + { + var elemType = memArrType.ElementType; + var elemSize = elemType.IsValueType ? Math.Max(1, (int)TypeSizes.UnboxedSize(elemType, 8)) : 8; + var elemIdx = (int)((memory.Addend - 0x20) / elemSize); + var memScratch = new CilLocalVariable(elemType.ToTypeSignature()); + method.CilMethodBody!.LocalVariables.Add(memScratch); + instructions.Add(CilOpCodes.Stloc, memScratch); + LoadLocal(memArrLocal, method, locals); + instructions.Add(CilOpCodes.Ldc_I4, elemIdx); + instructions.Add(CilOpCodes.Ldloc, memScratch); + instructions.Add(CilOpCodes.Stelem, elemType.ToTypeSignature().ToTypeDefOrRef()); + break; + } if (memory.Index == null && memory.Addend == 0 && memory.Scale == 0 && memory.Base is LocalVariable local2) { // Can pointer assignments just be ignored because it's C#? (Move [local], 123) - instructions.Add(CilOpCodes.Stloc, locals[local2]); + instructions.Add(CilOpCodes.Stloc, GetOrCreateLocal(local2, method, locals)); break; } instructions.Add(CilOpCodes.Pop); diff --git a/Cpp2IL.Core/InstructionSets/NewArmV8InstructionSet.cs b/Cpp2IL.Core/InstructionSets/NewArmV8InstructionSet.cs index 0ba9188f1..6226ac935 100644 --- a/Cpp2IL.Core/InstructionSets/NewArmV8InstructionSet.cs +++ b/Cpp2IL.Core/InstructionSets/NewArmV8InstructionSet.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Disarm; @@ -13,6 +14,8 @@ namespace Cpp2IL.Core.InstructionSets; public class NewArmV8InstructionSet : Cpp2IlInstructionSet { + private readonly ConcurrentDictionary DataReferences, IReadOnlyList CallTargets)> _throwHelperCache = new(); + [ThreadStatic] private static Dictionary? adrpOffsets; @@ -52,23 +55,30 @@ public override BinarySlice GetRawBytesForMethod(MethodAnalysisContext context, if (startOfNextFunction > 0) { - var startRaw = (int)binary.MapVirtualAddressToRaw(context.UnderlyingPointer); - if (startRaw > 0 && startRaw + count <= binary.RawLength) - return new BinarySlice(binary, startRaw, count); + if (binary.TryMapVirtualAddressToRaw(context.UnderlyingPointer, out var startRaw64)) + { + var startRaw = (int)startRaw64; + if (startRaw > 0 && startRaw + count <= binary.RawLength) + return new BinarySlice(binary, startRaw, count); + } } } var result = NewArm64Utils.GetArm64MethodBodyAtVirtualAddress(context.AppContext, context.UnderlyingPointer); var lastInsn = result.LastValid(); - var start = (int)binary.MapVirtualAddressToRaw(context.UnderlyingPointer); + if (!binary.TryMapVirtualAddressToRaw(context.UnderlyingPointer, out var start64) || + !binary.TryMapVirtualAddressToRaw(lastInsn.Address, out var lastInsnRaw64)) + return new BinarySlice(binary, 0, 0); + + var start = (int)start64; // Map the last instruction (always within segment) and add 4 (ARM64 instruction size). // This avoids mapping endVa which may land exactly at a segment boundary gap. - var end = (int)binary.MapVirtualAddressToRaw(lastInsn.Address) + 4; + var end = (int)lastInsnRaw64 + 4; //Sanity check - if (start < 0 || end < 0 || start >= binary.RawLength || end >= binary.RawLength) - throw new Exception($"Failed to map virtual address 0x{context.UnderlyingPointer:X} to raw address for method {context!.DeclaringType?.FullName}/{context.Name} - start: 0x{start:X}, end: 0x{end:X} are out of bounds for length {binary.RawLength}."); + if (start < 0 || end < 0 || start >= binary.RawLength || end >= binary.RawLength || end < start) + return new BinarySlice(binary, 0, 0); return new BinarySlice(binary, start, end - start); } @@ -80,18 +90,30 @@ public override List GetParameterOperandsFromMethod(MethodAnalysisCont public override (IReadOnlyList DataReferences, IReadOnlyList CallTargets) InspectPotentialThrowHelper(ApplicationAnalysisContext context, ulong address) { + if (address == 0) + return ([], []); + + if (_throwHelperCache.TryGetValue(address, out var cached)) + return cached; + //Deliberately not calling NewArm64Utils here, it's too slow const int maxInstructions = 48; var binary = context.Binary; - var rawStart = (int)binary.MapVirtualAddressToRaw(address); - if (rawStart <= 0) + if (!binary.TryMapVirtualAddressToRaw(address, out var rawStart64) || rawStart64 <= 0) + { + _throwHelperCache[address] = ([], []); return ([], []); + } + var rawStart = (int)rawStart64; var content = binary.GetRawBinaryContent(); var window = System.Math.Min(maxInstructions * 4, content.Length - rawStart); if (window < 4) + { + _throwHelperCache[address] = ([], []); return ([], []); + } List body; try @@ -100,6 +122,7 @@ public override (IReadOnlyList DataReferences, IReadOnlyList CallT } catch { + _throwHelperCache[address] = ([], []); return ([], []); } @@ -121,6 +144,7 @@ public override (IReadOnlyList DataReferences, IReadOnlyList CallT dataReferences.Add((ulong)((long)insn.Address + insn.Op1Imm)); break; case Arm64Mnemonic.BL: + case Arm64Mnemonic.B when insn.MnemonicConditionCode is Arm64ConditionCode.NONE or Arm64ConditionCode.AL: callTargets.Add(insn.BranchTarget); break; } @@ -133,7 +157,9 @@ public override (IReadOnlyList DataReferences, IReadOnlyList CallT break; } - return (dataReferences, callTargets); + var res = (dataReferences, callTargets); + _throwHelperCache[address] = res; + return res; } public override List GetIsilFromMethod(MethodAnalysisContext context) @@ -542,8 +568,35 @@ void EmitConditionalAssign(Arm64ConditionCode condition, Action emitTrueValue, A break; } + // ADRP page + immediate offset computes an absolute constant address + if (instruction.Op2Kind == Arm64OperandKind.Immediate && adrpOffsets!.TryGetValue(NormalizeRegister(instruction.Op1Reg), out var page) && !setsFlags) + { + var target = isSubtract ? (long)page - instruction.Op2Imm : (long)page + instruction.Op2Imm; + Add(address, OpCode.Move, ConvertOperand(instruction, 0), Imm(target)); + adrpOffsets[NormalizeRegister(instruction.Op0Reg)] = (ulong)target; + break; + } + adrpOffsets!.Remove(NormalizeRegister(instruction.Op0Reg)); + var src1 = ConvertOperand(instruction, 1); var src2 = ConvertOperand(instruction, 2); + + if (instruction.Op2Kind == Arm64OperandKind.Register && instruction.Op3Imm > 0) + { + if (instruction.FinalOpShiftType == Arm64ShiftType.LSL) + { + var shifted = new Register(null, $"TEMP_{instruction.Op2Reg}_LSL"); + Add(address, OpCode.ShiftLeft, shifted, src2, Imm(instruction.Op3Imm)); + src2 = shifted; + } + else if (instruction.FinalOpShiftType is Arm64ShiftType.LSR or Arm64ShiftType.ASR) + { + var shifted = new Register(null, $"TEMP_{instruction.Op2Reg}_SHR"); + Add(address, OpCode.ShiftRight, shifted, src2, Imm(instruction.Op3Imm)); + src2 = shifted; + } + } + // a discarded result means this is only about the flags var dest = IsReg31(instruction.Op0Reg) ? new Register(null, "TEMP") : ConvertOperand(instruction, 0); @@ -799,12 +852,9 @@ void EmitConditionalAssign(Arm64ConditionCode condition, Action emitTrueValue, A { var target = (ulong)((long)address + instruction.Op1Imm); var temp = new Register(null, "TEMP"); + var op = instruction.Mnemonic == Arm64Mnemonic.CBZ ? OpCode.CheckEqual : OpCode.CheckNotEqual; - Add(address, OpCode.CheckEqual, temp, ConvertOperand(instruction, 0), Imm(0)); - - if (instruction.Mnemonic == Arm64Mnemonic.CBNZ) - Add(address, OpCode.Not, temp, temp); - + Add(address, op, temp, ConvertOperand(instruction, 0), Imm(0)); Add(address, OpCode.ConditionalJump, Imm(target), temp); break; } @@ -813,12 +863,17 @@ void EmitConditionalAssign(Arm64ConditionCode condition, Action emitTrueValue, A { var target = (ulong)((long)address + instruction.Op2Imm); var temp = new Register(null, "TEMP"); + var op = instruction.Mnemonic == Arm64Mnemonic.TBZ ? OpCode.CheckEqual : OpCode.CheckNotEqual; - Add(address, OpCode.And, temp, ConvertOperand(instruction, 0), Imm(1L << (int)instruction.Op1Imm)); - Add(address, OpCode.CheckEqual, temp, temp, Imm(0)); - - if (instruction.Mnemonic == Arm64Mnemonic.TBNZ) - Add(address, OpCode.Not, temp, temp); + if (instruction.Op1Imm == 0) + { + Add(address, op, temp, ConvertOperand(instruction, 0), Imm(0)); + } + else + { + Add(address, OpCode.And, temp, ConvertOperand(instruction, 0), Imm(1L << (int)instruction.Op1Imm)); + Add(address, op, temp, temp, Imm(0)); + } Add(address, OpCode.ConditionalJump, Imm(target), temp); break; @@ -887,8 +942,8 @@ void EmitConditionalAssign(Arm64ConditionCode condition, Action emitTrueValue, A break; } - // any register write invalidates a tracked ADRP page address (ADRP itself just set one) - if (instruction.Mnemonic != Arm64Mnemonic.ADRP && instruction.Op0Kind == Arm64OperandKind.Register) + // any register write invalidates a tracked ADRP page address (ADRP itself just set one, ADD handled in its case) + if (instruction.Mnemonic != Arm64Mnemonic.ADRP && instruction.Mnemonic != Arm64Mnemonic.ADD && instruction.Op0Kind == Arm64OperandKind.Register) adrpOffsets!.Remove(NormalizeRegister(instruction.Op0Reg)); if (instruction.MemIndexMode != Arm64MemoryIndexMode.Offset && instruction.MemBase != Arm64Register.INVALID) adrpOffsets!.Remove(NormalizeRegister(instruction.MemBase)); diff --git a/Cpp2IL.Core/Model/Contexts/MethodAnalysisContext.cs b/Cpp2IL.Core/Model/Contexts/MethodAnalysisContext.cs index d47abcef4..c95a6d2b2 100644 --- a/Cpp2IL.Core/Model/Contexts/MethodAnalysisContext.cs +++ b/Cpp2IL.Core/Model/Contexts/MethodAnalysisContext.cs @@ -70,7 +70,7 @@ public class MethodAnalysisContext : HasGenericParameters, IMethodInfoProvider, public List AnalysisWarnings = []; - public static int MaxMethodSizeBytes = 30000; // 30KB + public static int MaxMethodSizeBytes = -1; public List Parameters = []; @@ -373,6 +373,15 @@ public void Analyze() StackAnalyzer.Analyze(this); + var blockCount = ControlFlowGraph.Blocks.Count; + + if (blockCount > 25000) + { + Logger.WarnNewline($"Method {FullName} has {blockCount} blocks, which exceeds absolute limits (>25,000). Filling with clean stub to avoid crash."); + ConvertedIsil = []; + return; + } + // Dominator info must be computed after stack analysis, which removes unreachable/empty // blocks and would otherwise leave the dominator tree out of sync with the graph SSA sees. DominatorInfo = new DominatorInfo(ControlFlowGraph); @@ -444,6 +453,7 @@ public void Analyze() // Runs late so the array type and length reach the allocation call as operands after copy propagation has inlined them ArrayRecovery.Run(this); + DeadCodeEliminator.Run(this); LocalVariables.TypeAddressedLocals(this); @@ -458,6 +468,12 @@ public void Analyze() DeadCodeEliminator.Run(this); LocalVariables.RemoveUnused(this); + + if (blockCount > 1000) + { + // Low-memory cleanup immediately after finishing a heavy method + GC.Collect(2, GCCollectionMode.Forced, false); + } } public void AddWarning(string warning) => AnalysisWarnings.Add(warning); diff --git a/Cpp2IL.Core/OutputFormats/AsmResolverDllOutputFormat.cs b/Cpp2IL.Core/OutputFormats/AsmResolverDllOutputFormat.cs index 26ad28477..f9f71f808 100644 --- a/Cpp2IL.Core/OutputFormats/AsmResolverDllOutputFormat.cs +++ b/Cpp2IL.Core/OutputFormats/AsmResolverDllOutputFormat.cs @@ -5,7 +5,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; +using AsmResolver; using AsmResolver.DotNet; using AsmResolver.DotNet.Builder; using AsmResolver.PE.Builder; @@ -51,23 +53,29 @@ public sealed override void DoOutput(ApplicationAnalysisContext context, string if (!Directory.Exists(outputRoot)) Directory.CreateDirectory(outputRoot); - //Convert assembly definitions to PE files - var peImagesToWrite = ret - .AsParallel() - .Select(a => (image: a.ManifestModule!.ToPEImage(new ManagedPEImageBuilder()), name: a.ManifestModule.Name!)) - .ToList(); + //Convert assembly definitions to PE files and write them to disk + var fileBuilder = new ManagedPEFileBuilder(); + var imageBuilder = new ManagedPEImageBuilder(EmptyErrorListener.Instance); - Logger.VerboseNewline($"{(DateTime.Now - start).TotalMilliseconds:F1}ms", "DllOutput"); + foreach (var assembly in ret) + { + if (assembly.ManifestModule is not { } module) + continue; - start = DateTime.Now; - Logger.Verbose("Building and writing managed PE files to disk...", "DllOutput"); + var name = module.Name; + if (string.IsNullOrEmpty(name)) + continue; - //Save them - var fileBuilder = new ManagedPEFileBuilder(); - foreach (var (image, name) in peImagesToWrite) - { - var dllPath = Path.Combine(outputRoot, name); - fileBuilder.CreateFile(image).Write(dllPath); + try + { + var image = module.ToPEImage(imageBuilder); + var dllPath = Path.Combine(outputRoot, name); + fileBuilder.CreateFile(image).Write(dllPath); + } + catch (Exception ex) + { + Logger.WarnNewline($"Failed to write PE image for {name}: {ex.Message}", "DllOutput"); + } } Logger.VerboseNewline($"{(DateTime.Now - start).TotalMilliseconds:F1}ms", "DllOutput"); diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..8acd47961 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,5 @@ + + + local + + diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 000000000..dd786584b --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,28 @@ + + + + + README.md + + + + + + + + README_CORE.md + + + + + + + + README.md + + + + + + +