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

SamboyCoding / Cpp2IL / 21104268457

18 Jan 2026 02:00AM UTC coverage: 34.371% (+0.01%) from 34.357%
21104268457

push

github

SamboyCoding
Change the meaning of MethodAnalysisContext::Overrides

It now specifically refers to methods that use `.override` in IL.

1818 of 6636 branches covered (27.4%)

Branch coverage included in aggregate %.

33 of 38 new or added lines in 2 files covered. (86.84%)

3 existing lines in 1 file now uncovered.

4209 of 10899 relevant lines covered (38.62%)

201213.77 hits per line

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

55.63
/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");
1,002,888!
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 = [];
864,100✔
57

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

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

65
    public bool IsVirtual => (Attributes & MethodAttributes.Virtual) != 0;
332✔
66

67
    public bool IsAbstract => (Attributes & MethodAttributes.Abstract) != 0;
×
68

69
    public bool IsNewSlot => (Attributes & MethodAttributes.NewSlot) != 0;
332✔
70

71
    protected override int CustomAttributeIndex => Definition?.customAttributeIndex ?? throw new("Subclasses of MethodAnalysisContext should override CustomAttributeIndex if they have custom attributes");
435,150!
72

73
    public override AssemblyAnalysisContext CustomAttributeAssembly => DeclaringType?.DeclaringAssembly ?? throw new("Subclasses of MethodAnalysisContext should override CustomAttributeAssembly if they have custom attributes");
1,108,468!
74

75
    public override string DefaultName => Definition?.Name ?? throw new("Subclasses of MethodAnalysisContext should override DefaultName");
87,702!
76

77
    public string FullName => DeclaringType == null ? Name : $"{DeclaringType.FullName}::{Name}";
37!
78

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

81
    public virtual MethodAttributes DefaultAttributes => Definition?.Attributes ?? throw new($"Subclasses of MethodAnalysisContext should override {nameof(DefaultAttributes)}");
262,411!
82

83
    public virtual MethodAttributes? OverrideAttributes { get; set; }
262,411✔
84

85
    public MethodAttributes Attributes
86
    {
87
        get => OverrideAttributes ?? DefaultAttributes;
262,411!
88
        set => OverrideAttributes = value;
×
89
    }
90

91
    public virtual MethodImplAttributes DefaultImplAttributes => Definition?.MethodImplAttributes ?? throw new($"Subclasses of MethodAnalysisContext should override {nameof(DefaultImplAttributes)}");
87,030!
92

93
    public virtual MethodImplAttributes? OverrideImplAttributes { get; set; }
87,030✔
94

95
    public MethodImplAttributes ImplAttributes
96
    {
97
        get => OverrideImplAttributes ?? DefaultImplAttributes;
87,030!
98
        set => OverrideImplAttributes = value;
×
99
    }
100

101
    public MethodAttributes Visibility
102
    {
103
        get
104
        {
105
            return Attributes & MethodAttributes.MemberAccessMask;
×
106
        }
107
        set
108
        {
109
            Attributes = (Attributes & ~MethodAttributes.MemberAccessMask) | (value & MethodAttributes.MemberAccessMask);
×
110
        }
×
111
    }
112

113
    private List<GenericParameterTypeAnalysisContext>? _genericParameters;
114
    public override List<GenericParameterTypeAnalysisContext> GenericParameters
115
    {
116
        get
117
        {
118
            // Lazy load the generic parameters
119
            _genericParameters ??= Definition?.GenericContainer?.GenericParameters.Select(p => new GenericParameterTypeAnalysisContext(p, this)).ToList() ?? [];
534,527!
120
            return _genericParameters;
528,790✔
121
        }
122
    }
123

124
    private ushort Slot => Definition?.slot ?? ushort.MaxValue;
25,514!
125

126
    public virtual TypeAnalysisContext DefaultReturnType => DeclaringType?.DeclaringAssembly.ResolveIl2CppType(Definition?.RawReturnType) ?? throw new($"Subclasses of MethodAnalysisContext should override {nameof(DefaultReturnType)}");
441,599!
127

128
    public TypeAnalysisContext? OverrideReturnType { get; set; }
441,602✔
129

130
    //TODO Support custom attributes on return types (v31 feature)
131
    public TypeAnalysisContext ReturnType
132
    {
133
        get => OverrideReturnType ?? DefaultReturnType;
441,602✔
134
        set => OverrideReturnType = value;
×
135
    }
136
    
137
    protected Memory<byte>? rawMethodBody;
138

139
    public MethodAnalysisContext? BaseMethod
140
    {
141
        get
142
        {
143
            if (Definition == null)
335!
NEW
144
                return null;
×
145

146
            var vtable = DeclaringType?.Definition?.VTable;
335!
147
            if (vtable == null)
335!
NEW
148
                return null;
×
149

150
            for (var i = 0; i < vtable.Length; ++i)
744✔
151
            {
152
                var vtableEntry = vtable[i];
39✔
153
                if (vtableEntry is null or { Type: not MetadataUsageType.MethodDef } || vtableEntry.AsMethod() != Definition)
39!
154
                    continue;
155

156
                var baseType = DeclaringType?.DefaultBaseType;
5!
157
                while (baseType is not null)
9✔
158
                {
159
                    if (TryGetMethodForSlot(baseType, i, out var method))
6✔
160
                    {
161
                        return method;
2✔
162
                    }
163
                    baseType = baseType.DefaultBaseType;
4✔
164
                }
165
            }
166
            return null;
333✔
167
        }
168
    }
169

170
    private List<MethodAnalysisContext>? _overrides;
171

172
    /// <summary>
173
    /// The set of interface methods which this method explicitly overrides.
174
    /// </summary>
175
    public List<MethodAnalysisContext> Overrides
176
    {
177
        get
178
        {
179
            // Lazy load the overrides
180
            return _overrides ??= GetOverrides().ToList();
18,376✔
181
        }
182
    }
183

184
    private IEnumerable<MethodAnalysisContext> GetOverrides()
185
    {
186
        if (Definition == null)
18,376!
187
            return [];
×
188

189
        var declaringTypeDefinition = DeclaringType?.Definition;
18,376!
190
        if (declaringTypeDefinition == null)
18,376!
191
            return [];
×
192

193
        var vtable = declaringTypeDefinition.VTable;
18,376✔
194
        if (vtable == null)
18,376!
195
            return [];
×
196

197
        return GetOverriddenMethods(declaringTypeDefinition, vtable);
18,376✔
198

199
        IEnumerable<MethodAnalysisContext> GetOverriddenMethods(Il2CppTypeDefinition declaringTypeDefinition, MetadataUsage?[] vtable)
200
        {
201
            for (var i = 0; i < vtable.Length; ++i)
684,280✔
202
            {
203
                var vtableEntry = vtable[i];
323,764✔
204
                if (vtableEntry is null or { Type: not MetadataUsageType.MethodDef })
323,764✔
205
                    continue;
206

207
                if (vtableEntry.AsMethod() != Definition)
318,154✔
208
                    continue;
209

210
                // Interface inheritance
211
                foreach (var interfaceOffset in declaringTypeDefinition.InterfaceOffsets)
34,510✔
212
                {
213
                    if (i >= interfaceOffset.offset)
14,135✔
214
                    {
215
                        var interfaceTypeContext = interfaceOffset.Type.ToContext(CustomAttributeAssembly);
8,738✔
216
                        if (interfaceTypeContext != null && TryGetMethodForSlot(interfaceTypeContext, i - interfaceOffset.offset, out var method))
8,738✔
217
                        {
218
                            yield return method;
3,119✔
219
                        }
220
                    }
221
                }
222
            }
223
        }
18,376✔
224
    }
225

226
    private static bool TryGetMethodForSlot(TypeAnalysisContext declaringType, int slot, [NotNullWhen(true)] out MethodAnalysisContext? method)
227
    {
228
        if (declaringType is GenericInstanceTypeAnalysisContext genericInstanceType)
8,744✔
229
        {
230
            var genericMethod = genericInstanceType.GenericType.Methods.FirstOrDefault(m => m.Slot == slot);
6,253✔
231
            if (genericMethod is not null)
1,727✔
232
            {
233
                method = new ConcreteGenericMethodAnalysisContext(genericMethod, genericInstanceType.GenericArguments, []);
328✔
234
                return true;
328✔
235
            }
236
        }
237
        else
238
        {
239
            var baseMethod = declaringType.Methods.FirstOrDefault(m => m.Slot == slot);
28,005✔
240
            if (baseMethod is not null)
7,017✔
241
            {
242
                method = baseMethod;
2,793✔
243
                return true;
2,793✔
244
            }
245
        }
246

247
        method = null;
5,623✔
248
        return false;
5,623✔
249
    }
250

251
    private static readonly List<IBlockProcessor> blockProcessors =
×
252
    [
×
253
        new MetadataProcessor(),
×
254
        new CallProcessor()
×
255
    ];
×
256

257
    public MethodAnalysisContext(Il2CppMethodDefinition? definition, TypeAnalysisContext parent) : base(definition?.token ?? 0, parent.AppContext)
864,100✔
258
    {
259
        DeclaringType = parent;
864,100✔
260
        Definition = definition;
864,100✔
261

262
        if (Definition != null)
864,100✔
263
        {
264
            InitCustomAttributeData();
509,604✔
265

266
            for (var i = 0; i < Definition.InternalParameterData!.Length; i++)
2,186,874✔
267
            {
268
                var parameterDefinition = Definition.InternalParameterData![i];
583,833✔
269
                Parameters.Add(new(parameterDefinition, i, this));
583,833✔
270
            }
271
        }
272
        else
273
            rawMethodBody = Array.Empty<byte>();
354,496✔
274
    }
354,496✔
275

276
    [MemberNotNull(nameof(rawMethodBody))]
277
    public void EnsureRawBytes()
278
    {
279
        rawMethodBody ??= InitRawBytes();
509,604✔
280
    }
509,604✔
281

282
    private Memory<byte> InitRawBytes()
283
    {
284
        //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.
285
        //E.g. UnityEngine.Purchasing.AppleCore.dll: UnityEngine.Purchasing.INativeAppleStore::SetUnityPurchasingCallback on among us (itch.io build)
286
        if (Definition != null && Definition.MethodPointer != 0 && !Definition.Attributes.HasFlag(MethodAttributes.Abstract))
509,604✔
287
        {
288
            var ret = AppContext.InstructionSet.GetRawBytesForMethod(this, false);
493,284✔
289

290
            if (ret.Length == 0)
493,284✔
291
            {
292
                Logger.VerboseNewline("\t\t\tUnexpectedly got 0-byte method body for " + this + $". Pointer was 0x{Definition.MethodPointer:X}", "MAC");
37!
293
            }
294

295
            return ret;
493,284✔
296
        }
297
        else
298
            return Array.Empty<byte>();
16,320✔
299
    }
300

301
    protected MethodAnalysisContext(ApplicationAnalysisContext context) : base(0, context)
×
302
    {
303
        rawMethodBody = Array.Empty<byte>();
×
304
    }
×
305

306
    [MemberNotNull(nameof(ConvertedIsil))]
307
    public void Analyze()
308
    {
309
        if (ConvertedIsil != null)
×
310
            return;
×
311

312
        if (UnderlyingPointer == 0)
×
313
        {
314
            ConvertedIsil = [];
×
315
            return;
×
316
        }
317

318
        ConvertedIsil = AppContext.InstructionSet.GetIsilFromMethod(this);
×
319

320
        if (ConvertedIsil.Count == 0)
×
321
            return; //Nothing to do, empty function
×
322

323
        ControlFlowGraph = new ISILControlFlowGraph();
×
324
        ControlFlowGraph.Build(ConvertedIsil);
×
325

326
        // Post step to convert metadata usage. Ldstr Opcodes etc.
327
        foreach (var block in ControlFlowGraph.Blocks)
×
328
        {
329
            foreach (var converter in blockProcessors)
×
330
            {
331
                converter.Process(this, block);
×
332
            }
333
        }
334
    }
×
335

336
    public void ReleaseAnalysisData()
337
    {
338
        ConvertedIsil = null;
×
339
        ControlFlowGraph = null;
×
340
    }
×
341

342
    public ConcreteGenericMethodAnalysisContext MakeGenericInstanceMethod(params IEnumerable<TypeAnalysisContext> methodGenericParameters)
343
    {
344
        if (this is ConcreteGenericMethodAnalysisContext methodOnGenericInstanceType)
×
345
        {
346
            return new ConcreteGenericMethodAnalysisContext(methodOnGenericInstanceType.BaseMethodContext, methodOnGenericInstanceType.TypeGenericParameters, methodGenericParameters);
×
347
        }
348
        else
349
        {
350
            return new ConcreteGenericMethodAnalysisContext(this, [], methodGenericParameters);
×
351
        }
352
    }
353

354
    public ConcreteGenericMethodAnalysisContext MakeConcreteGenericMethod(IEnumerable<TypeAnalysisContext> typeGenericParameters, IEnumerable<TypeAnalysisContext> methodGenericParameters)
355
    {
356
        if (this is ConcreteGenericMethodAnalysisContext)
×
357
        {
358
            throw new InvalidOperationException($"Attempted to make a {nameof(ConcreteGenericMethodAnalysisContext)} concrete: {this}");
×
359
        }
360
        else
361
        {
362
            return new ConcreteGenericMethodAnalysisContext(this, typeGenericParameters, methodGenericParameters);
×
363
        }
364
    }
365

366
    public override string ToString() => $"Method: {FullName}";
37✔
367

368
    #region StableNameDot implementation
369

370
    ITypeInfoProvider IMethodInfoProvider.ReturnType =>
371
        Definition!.RawReturnType!.ThisOrElementIsGenericParam()
×
372
            ? new GenericParameterTypeInfoProviderWrapper(Definition.RawReturnType!.GetGenericParamName())
×
373
            : TypeAnalysisContext.GetSndnProviderForType(AppContext, Definition!.RawReturnType);
×
374

375
    IEnumerable<IParameterInfoProvider> IMethodInfoProvider.ParameterInfoProviders => Parameters;
×
376

377
    string IMethodInfoProvider.MethodName => Name;
×
378

379
    MethodAttributes IMethodInfoProvider.MethodAttributes => Attributes;
×
380

381
    MethodSemantics IMethodInfoProvider.MethodSemantics
382
    {
383
        get
384
        {
385
            if (DeclaringType != null)
×
386
            {
387
                //This one is a bit trickier, as il2cpp doesn't use semantics.
388
                foreach (var prop in DeclaringType.Properties)
×
389
                {
390
                    if (prop.Getter == this)
×
391
                        return MethodSemantics.Getter;
×
392
                    if (prop.Setter == this)
×
393
                        return MethodSemantics.Setter;
×
394
                }
395

396
                foreach (var evt in DeclaringType.Events)
×
397
                {
398
                    if (evt.Adder == this)
×
399
                        return MethodSemantics.AddOn;
×
400
                    if (evt.Remover == this)
×
401
                        return MethodSemantics.RemoveOn;
×
402
                    if (evt.Invoker == this)
×
403
                        return MethodSemantics.Fire;
×
404
                }
405
            }
406

407
            return 0;
×
408
        }
×
409
    }
410

411
    #endregion
412
}
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

© 2026 Coveralls, Inc