• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

SamboyCoding / Cpp2IL / 15144219583

20 May 2025 05:38PM UTC coverage: 34.28% (+0.2%) from 34.047%
15144219583

Pull #462

github

web-flow
Merge f80b990bc into 5807d2b6c
Pull Request #462: Support overriding member types

1799 of 6646 branches covered (27.07%)

Branch coverage included in aggregate %.

115 of 202 new or added lines in 33 files covered. (56.93%)

22 existing lines in 6 files now uncovered.

4197 of 10845 relevant lines covered (38.7%)

186399.11 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

56.42
/Cpp2IL.Core/Model/Contexts/MethodAnalysisContext.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Diagnostics.CodeAnalysis;
4
using System.Linq;
5
using System.Reflection;
6
using Cpp2IL.Core.Graphs;
7
using Cpp2IL.Core.Graphs.Processors;
8
using Cpp2IL.Core.ISIL;
9
using Cpp2IL.Core.Logging;
10
using Cpp2IL.Core.Utils;
11
using LibCpp2IL;
12
using LibCpp2IL.Metadata;
13
using StableNameDotNet.Providers;
14

15
namespace Cpp2IL.Core.Model.Contexts;
16

17
/// <summary>
18
/// Represents one method within the application. Can be analyzed to attempt to reconstruct the function body.
19
/// </summary>
20
public class MethodAnalysisContext : HasGenericParameters, IMethodInfoProvider
21
{
22
    /// <summary>
23
    /// The underlying metadata for the method.
24
    ///
25
    /// Nullable iff this is a subclass.
26
    /// </summary>
27
    public readonly Il2CppMethodDefinition? Definition;
28

29
    /// <summary>
30
    /// The analysis context for the declaring type of this method.
31
    /// </summary>
32
    public readonly TypeAnalysisContext? DeclaringType;
33

34
    /// <summary>
35
    /// The address of this method as defined in the underlying metadata.
36
    /// </summary>
37
    public virtual ulong UnderlyingPointer => Definition?.MethodPointer ?? throw new("Subclasses of MethodAnalysisContext should override UnderlyingPointer");
865,848!
38

39
    public ulong Rva => UnderlyingPointer == 0 || LibCpp2IlMain.Binary == null ? 0 : LibCpp2IlMain.Binary.GetRva(UnderlyingPointer);
×
40

41
    /// <summary>
42
    /// The raw method body as machine code in the active instruction set.
43
    /// </summary>
44
    public Memory<byte> RawBytes => rawMethodBody ??= InitRawBytes();
×
45

46
    /// <summary>
47
    /// The first-stage-analyzed Instruction-Set-Independent Language Instructions.
48
    /// </summary>
49
    public List<InstructionSetIndependentInstruction>? ConvertedIsil;
50

51
    /// <summary>
52
    /// The control flow graph for this method, if one is built.
53
    /// </summary>
54
    public ISILControlFlowGraph? ControlFlowGraph;
55

56
    public List<ParameterAnalysisContext> Parameters = [];
738,870✔
57

58
    /// <summary>
59
    /// Does this method return void?
60
    /// </summary>
NEW
61
    public bool IsVoid => ReturnType == AppContext.SystemTypes.SystemVoidType;
×
62

63
    public bool IsStatic => (Attributes & MethodAttributes.Static) != 0;
87,355✔
64

65
    protected override int CustomAttributeIndex => Definition?.customAttributeIndex ?? throw new("Subclasses of MethodAnalysisContext should override CustomAttributeIndex if they have custom attributes");
365,526!
66

67
    public override AssemblyAnalysisContext CustomAttributeAssembly => DeclaringType?.DeclaringAssembly ?? throw new("Subclasses of MethodAnalysisContext should override CustomAttributeAssembly if they have custom attributes");
968,522!
68

69
    public override string DefaultName => Definition?.Name ?? throw new("Subclasses of MethodAnalysisContext should override DefaultName");
87,698!
70

71
    public string FullName => DeclaringType == null ? Name : $"{DeclaringType.FullName}::{Name}";
33!
72

NEW
73
    public string FullNameWithSignature => $"{ReturnType.FullName} {FullName}({string.Join(", ", Parameters.Select(p => p.HumanReadableSignature))})";
×
74

75
    public virtual MethodAttributes DefaultAttributes => Definition?.Attributes ?? throw new($"Subclasses of MethodAnalysisContext should override {nameof(DefaultAttributes)}");
261,415!
76

77
    public virtual MethodAttributes? OverrideAttributes { get; set; }
261,415✔
78

79
    public virtual MethodAttributes Attributes => OverrideAttributes ?? DefaultAttributes;
261,415!
80

81
    public MethodAttributes Visibility
82
    {
83
        get
84
        {
NEW
85
            return Attributes & MethodAttributes.MemberAccessMask;
×
86
        }
87
        set
88
        {
NEW
89
            OverrideAttributes = (Attributes & ~MethodAttributes.MemberAccessMask) | (value & MethodAttributes.MemberAccessMask);
×
NEW
90
        }
×
91
    }
92

93
    public int ParameterCount => Parameters.Count;
10✔
94

95
    private List<GenericParameterTypeAnalysisContext>? _genericParameters;
96
    public override List<GenericParameterTypeAnalysisContext> GenericParameters
97
    {
98
        get
99
        {
100
            // Lazy load the generic parameters
101
            _genericParameters ??= Definition?.GenericContainer?.GenericParameters.Select(p => new GenericParameterTypeAnalysisContext(p, this)).ToList() ?? [];
485,803!
102
            return _genericParameters;
480,782✔
103
        }
104
    }
105

106
    public int GenericParameterCount => GenericParameters.Count;
338,335✔
107

108
    private ushort Slot => Definition?.slot ?? ushort.MaxValue;
75,705!
109

110
    public virtual TypeAnalysisContext DefaultReturnType => DeclaringType?.DeclaringAssembly.ResolveIl2CppType(Definition?.RawReturnType) ?? throw new($"Subclasses of MethodAnalysisContext should override {nameof(DefaultReturnType)}");
385,993!
111

112
    public TypeAnalysisContext? OverrideReturnType { get; set; }
385,996✔
113

114
    //TODO Support custom attributes on return types (v31 feature)
115
    public TypeAnalysisContext ReturnType => OverrideReturnType ?? DefaultReturnType;
385,996✔
116
    
117
    protected Memory<byte>? rawMethodBody;
118

119
    public MethodAnalysisContext? BaseMethod => Overrides.FirstOrDefault(m => m.DeclaringType?.IsInterface is false);
8!
120

121
    /// <summary>
122
    /// The set of methods which this method overrides.
123
    /// </summary>
124
    public virtual IEnumerable<MethodAnalysisContext> Overrides
125
    {
126
        get
127
        {
128
            if (Definition == null)
18,047!
129
                return [];
×
130

131
            var declaringTypeDefinition = DeclaringType?.Definition;
18,047!
132
            if (declaringTypeDefinition == null)
18,047!
133
                return [];
×
134

135
            var vtable = declaringTypeDefinition.VTable;
18,047✔
136
            if (vtable == null)
18,047!
137
                return [];
×
138

139
            return GetOverriddenMethods(declaringTypeDefinition, vtable);
18,047✔
140

141
            bool TryGetMethodForSlot(TypeAnalysisContext declaringType, int slot, [NotNullWhen(true)] out MethodAnalysisContext? method)
142
            {
143
                if (declaringType is GenericInstanceTypeAnalysisContext genericInstanceType)
13,520✔
144
                {
145
                    var genericMethod = genericInstanceType.GenericType.Methods.FirstOrDefault(m => m.Slot == slot);
7,102✔
146
                    if (genericMethod is not null)
1,802✔
147
                    {
148
                        method = new ConcreteGenericMethodAnalysisContext(genericMethod, genericInstanceType.GenericArguments.ToArray(), []);
330✔
149
                        return true;
330✔
150
                    }
151
                }
152
                else
153
                {
154
                    var baseMethod = declaringType.Methods.FirstOrDefault(m => m.Slot == slot);
82,123✔
155
                    if (baseMethod is not null)
11,718✔
156
                    {
157
                        method = baseMethod;
2,830✔
158
                        return true;
2,830✔
159
                    }
160
                }
161

162
                method = null;
10,360✔
163
                return false;
10,360✔
164
            }
165

166
            IEnumerable<MethodAnalysisContext> GetOverriddenMethods(Il2CppTypeDefinition declaringTypeDefinition, MetadataUsage?[] vtable)
167
            {
168
                for (var i = 0; i < vtable.Length; ++i)
683,696✔
169
                {
170
                    var vtableEntry = vtable[i];
323,803✔
171
                    if (vtableEntry is null or { Type: not MetadataUsageType.MethodDef })
323,803✔
172
                        continue;
173

174
                    if (vtableEntry.AsMethod() != Definition)
318,193✔
175
                        continue;
176

177
                    // Normal inheritance
178
                    var baseType = DeclaringType?.BaseType;
3,125!
179
                    while (baseType is not null)
7,853✔
180
                    {
181
                        if (TryGetMethodForSlot(baseType, i, out var method))
4,766✔
182
                        {
183
                            yield return method;
38✔
184
                            break; // We only want direct overrides, not the entire inheritance chain.
36✔
185
                        }
186
                        baseType = baseType.BaseType;
4,728✔
187
                    }
188

189
                    // Interface inheritance
190
                    foreach (var interfaceOffset in declaringTypeDefinition.InterfaceOffsets)
34,564✔
191
                    {
192
                        if (i >= interfaceOffset.offset)
14,159✔
193
                        {
194
                            var interfaceTypeContext = interfaceOffset.Type.ToContext(CustomAttributeAssembly);
8,754✔
195
                            if (interfaceTypeContext != null && TryGetMethodForSlot(interfaceTypeContext, i - interfaceOffset.offset, out var method))
8,754✔
196
                            {
197
                                yield return method;
3,122✔
198
                            }
199
                        }
200
                    }
201
                }
202
            }
18,045✔
203
        }
204
    }
205

206
    private static readonly List<IBlockProcessor> blockProcessors =
×
207
    [
×
208
        new MetadataProcessor(),
×
209
        new CallProcessor()
×
210
    ];
×
211

212
    public MethodAnalysisContext(Il2CppMethodDefinition? definition, TypeAnalysisContext parent) : base(definition?.token ?? 0, parent.AppContext)
738,870✔
213
    {
214
        DeclaringType = parent;
738,870✔
215
        Definition = definition;
738,870✔
216

217
        if (Definition != null)
738,870✔
218
        {
219
            InitCustomAttributeData();
439,980✔
220

221
            for (var i = 0; i < Definition.InternalParameterData!.Length; i++)
1,890,450✔
222
            {
223
                var parameterDefinition = Definition.InternalParameterData![i];
505,245✔
224
                Parameters.Add(new(parameterDefinition, i, this));
505,245✔
225
            }
226
        }
227
        else
228
            rawMethodBody = Array.Empty<byte>();
298,890✔
229
    }
298,890✔
230

231
    [MemberNotNull(nameof(rawMethodBody))]
232
    public void EnsureRawBytes()
233
    {
234
        rawMethodBody ??= InitRawBytes();
439,980✔
235
    }
439,980✔
236

237
    private Memory<byte> InitRawBytes()
238
    {
239
        //Some abstract methods (on interfaces, no less) apparently have a body? Unity doesn't support default interface methods so idk what's going on here.
240
        //E.g. UnityEngine.Purchasing.AppleCore.dll: UnityEngine.Purchasing.INativeAppleStore::SetUnityPurchasingCallback on among us (itch.io build)
241
        if (Definition != null && Definition.MethodPointer != 0 && !Definition.Attributes.HasFlag(MethodAttributes.Abstract))
439,980✔
242
        {
243
            var ret = AppContext.InstructionSet.GetRawBytesForMethod(this, false);
425,868✔
244

245
            if (ret.Length == 0)
425,868✔
246
            {
247
                Logger.VerboseNewline("\t\t\tUnexpectedly got 0-byte method body for " + this + $". Pointer was 0x{Definition.MethodPointer:X}", "MAC");
33!
248
            }
249

250
            return ret;
425,868✔
251
        }
252
        else
253
            return Array.Empty<byte>();
14,112✔
254
    }
255

256
    protected MethodAnalysisContext(ApplicationAnalysisContext context) : base(0, context)
×
257
    {
258
        rawMethodBody = Array.Empty<byte>();
×
259
    }
×
260

261
    [MemberNotNull(nameof(ConvertedIsil))]
262
    public void Analyze()
263
    {
264
        if (ConvertedIsil != null)
×
265
            return;
×
266

267
        if (UnderlyingPointer == 0)
×
268
        {
269
            ConvertedIsil = [];
×
270
            return;
×
271
        }
272

273
        ConvertedIsil = AppContext.InstructionSet.GetIsilFromMethod(this);
×
274

275
        if (ConvertedIsil.Count == 0)
×
276
            return; //Nothing to do, empty function
×
277

278
        ControlFlowGraph = new ISILControlFlowGraph();
×
279
        ControlFlowGraph.Build(ConvertedIsil);
×
280

281
        // Post step to convert metadata usage. Ldstr Opcodes etc.
282
        foreach (var block in ControlFlowGraph.Blocks)
×
283
        {
284
            foreach (var converter in blockProcessors)
×
285
            {
286
                converter.Process(this, block);
×
287
            }
288
        }
289
    }
×
290

291
    public void ReleaseAnalysisData()
292
    {
293
        ConvertedIsil = null;
×
294
        ControlFlowGraph = null;
×
295
    }
×
296

297
    public override string ToString() => $"Method: {FullName}";
33✔
298

299
    #region StableNameDot implementation
300

301
    ITypeInfoProvider IMethodInfoProvider.ReturnType =>
302
        Definition!.RawReturnType!.ThisOrElementIsGenericParam()
×
303
            ? new GenericParameterTypeInfoProviderWrapper(Definition.RawReturnType!.GetGenericParamName())
×
304
            : TypeAnalysisContext.GetSndnProviderForType(AppContext, Definition!.RawReturnType);
×
305

306
    IEnumerable<IParameterInfoProvider> IMethodInfoProvider.ParameterInfoProviders => Parameters;
×
307

308
    string IMethodInfoProvider.MethodName => Name;
×
309

310
    MethodAttributes IMethodInfoProvider.MethodAttributes => Attributes;
×
311

312
    MethodSemantics IMethodInfoProvider.MethodSemantics
313
    {
314
        get
315
        {
316
            if (DeclaringType != null)
×
317
            {
318
                //This one is a bit trickier, as il2cpp doesn't use semantics.
319
                foreach (var prop in DeclaringType.Properties)
×
320
                {
321
                    if (prop.Getter == this)
×
322
                        return MethodSemantics.Getter;
×
323
                    if (prop.Setter == this)
×
324
                        return MethodSemantics.Setter;
×
325
                }
326

327
                foreach (var evt in DeclaringType.Events)
×
328
                {
329
                    if (evt.Adder == this)
×
330
                        return MethodSemantics.AddOn;
×
331
                    if (evt.Remover == this)
×
332
                        return MethodSemantics.RemoveOn;
×
333
                    if (evt.Invoker == this)
×
334
                        return MethodSemantics.Fire;
×
335
                }
336
            }
337

338
            return 0;
×
339
        }
×
340
    }
341

342
    #endregion
343
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc