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

SamboyCoding / Cpp2IL / 20487966407

24 Dec 2025 02:14PM UTC coverage: 34.324% (+0.05%) from 34.275%
20487966407

push

github

SamboyCoding
Add test for static classes

1796 of 6590 branches covered (27.25%)

Branch coverage included in aggregate %.

4196 of 10867 relevant lines covered (38.61%)

201837.39 hits per line

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

53.96
/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,102✔
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,486!
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,529!
120
            return _genericParameters;
528,792✔
121
        }
122
    }
123

124
    private ushort Slot => Definition?.slot ?? ushort.MaxValue;
75,705!
125

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

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

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

139
    public MethodAnalysisContext? BaseMethod => Overrides.FirstOrDefault(m => m.DeclaringType?.IsInterface is false);
340!
140

141
    /// <summary>
142
    /// The set of methods which this method overrides.
143
    /// </summary>
144
    public virtual IEnumerable<MethodAnalysisContext> Overrides
145
    {
146
        get
147
        {
148
            if (Definition == null)
18,711!
149
                return [];
×
150

151
            var declaringTypeDefinition = DeclaringType?.Definition;
18,711!
152
            if (declaringTypeDefinition == null)
18,711!
153
                return [];
×
154

155
            var vtable = declaringTypeDefinition.VTable;
18,711✔
156
            if (vtable == null)
18,711!
157
                return [];
×
158

159
            return GetOverriddenMethods(declaringTypeDefinition, vtable);
18,711✔
160

161
            bool TryGetMethodForSlot(TypeAnalysisContext declaringType, int slot, [NotNullWhen(true)] out MethodAnalysisContext? method)
162
            {
163
                if (declaringType is GenericInstanceTypeAnalysisContext genericInstanceType)
13,520✔
164
                {
165
                    var genericMethod = genericInstanceType.GenericType.Methods.FirstOrDefault(m => m.Slot == slot);
7,102✔
166
                    if (genericMethod is not null)
1,802✔
167
                    {
168
                        method = new ConcreteGenericMethodAnalysisContext(genericMethod, genericInstanceType.GenericArguments, []);
330✔
169
                        return true;
330✔
170
                    }
171
                }
172
                else
173
                {
174
                    var baseMethod = declaringType.Methods.FirstOrDefault(m => m.Slot == slot);
82,123✔
175
                    if (baseMethod is not null)
11,718✔
176
                    {
177
                        method = baseMethod;
2,830✔
178
                        return true;
2,830✔
179
                    }
180
                }
181

182
                method = null;
10,360✔
183
                return false;
10,360✔
184
            }
185

186
            IEnumerable<MethodAnalysisContext> GetOverriddenMethods(Il2CppTypeDefinition declaringTypeDefinition, MetadataUsage?[] vtable)
187
            {
188
                for (var i = 0; i < vtable.Length; ++i)
685,024✔
189
                {
190
                    var vtableEntry = vtable[i];
323,803✔
191
                    if (vtableEntry is null or { Type: not MetadataUsageType.MethodDef })
323,803✔
192
                        continue;
193

194
                    if (vtableEntry.AsMethod() != Definition)
318,193✔
195
                        continue;
196

197
                    // Normal inheritance
198
                    var baseType = DeclaringType?.BaseType;
3,125!
199
                    while (baseType is not null)
7,853✔
200
                    {
201
                        if (TryGetMethodForSlot(baseType, i, out var method))
4,766✔
202
                        {
203
                            yield return method;
38✔
204
                            break; // We only want direct overrides, not the entire inheritance chain.
36✔
205
                        }
206
                        baseType = baseType.BaseType;
4,728✔
207
                    }
208

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

226
    private static readonly List<IBlockProcessor> blockProcessors =
×
227
    [
×
228
        new MetadataProcessor(),
×
229
        new CallProcessor()
×
230
    ];
×
231

232
    public MethodAnalysisContext(Il2CppMethodDefinition? definition, TypeAnalysisContext parent) : base(definition?.token ?? 0, parent.AppContext)
864,102✔
233
    {
234
        DeclaringType = parent;
864,102✔
235
        Definition = definition;
864,102✔
236

237
        if (Definition != null)
864,102✔
238
        {
239
            InitCustomAttributeData();
509,604✔
240

241
            for (var i = 0; i < Definition.InternalParameterData!.Length; i++)
2,186,874✔
242
            {
243
                var parameterDefinition = Definition.InternalParameterData![i];
583,833✔
244
                Parameters.Add(new(parameterDefinition, i, this));
583,833✔
245
            }
246
        }
247
        else
248
            rawMethodBody = Array.Empty<byte>();
354,498✔
249
    }
354,498✔
250

251
    [MemberNotNull(nameof(rawMethodBody))]
252
    public void EnsureRawBytes()
253
    {
254
        rawMethodBody ??= InitRawBytes();
509,604✔
255
    }
509,604✔
256

257
    private Memory<byte> InitRawBytes()
258
    {
259
        //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.
260
        //E.g. UnityEngine.Purchasing.AppleCore.dll: UnityEngine.Purchasing.INativeAppleStore::SetUnityPurchasingCallback on among us (itch.io build)
261
        if (Definition != null && Definition.MethodPointer != 0 && !Definition.Attributes.HasFlag(MethodAttributes.Abstract))
509,604✔
262
        {
263
            var ret = AppContext.InstructionSet.GetRawBytesForMethod(this, false);
493,284✔
264

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

270
            return ret;
493,284✔
271
        }
272
        else
273
            return Array.Empty<byte>();
16,320✔
274
    }
275

276
    protected MethodAnalysisContext(ApplicationAnalysisContext context) : base(0, context)
×
277
    {
278
        rawMethodBody = Array.Empty<byte>();
×
279
    }
×
280

281
    [MemberNotNull(nameof(ConvertedIsil))]
282
    public void Analyze()
283
    {
284
        if (ConvertedIsil != null)
×
285
            return;
×
286

287
        if (UnderlyingPointer == 0)
×
288
        {
289
            ConvertedIsil = [];
×
290
            return;
×
291
        }
292

293
        ConvertedIsil = AppContext.InstructionSet.GetIsilFromMethod(this);
×
294

295
        if (ConvertedIsil.Count == 0)
×
296
            return; //Nothing to do, empty function
×
297

298
        ControlFlowGraph = new ISILControlFlowGraph();
×
299
        ControlFlowGraph.Build(ConvertedIsil);
×
300

301
        // Post step to convert metadata usage. Ldstr Opcodes etc.
302
        foreach (var block in ControlFlowGraph.Blocks)
×
303
        {
304
            foreach (var converter in blockProcessors)
×
305
            {
306
                converter.Process(this, block);
×
307
            }
308
        }
309
    }
×
310

311
    public void ReleaseAnalysisData()
312
    {
313
        ConvertedIsil = null;
×
314
        ControlFlowGraph = null;
×
315
    }
×
316

317
    public ConcreteGenericMethodAnalysisContext MakeGenericInstanceMethod(params IEnumerable<TypeAnalysisContext> methodGenericParameters)
318
    {
319
        if (this is ConcreteGenericMethodAnalysisContext methodOnGenericInstanceType)
×
320
        {
321
            return new ConcreteGenericMethodAnalysisContext(methodOnGenericInstanceType.BaseMethodContext, methodOnGenericInstanceType.TypeGenericParameters, methodGenericParameters);
×
322
        }
323
        else
324
        {
325
            return new ConcreteGenericMethodAnalysisContext(this, [], methodGenericParameters);
×
326
        }
327
    }
328

329
    public ConcreteGenericMethodAnalysisContext MakeConcreteGenericMethod(IEnumerable<TypeAnalysisContext> typeGenericParameters, IEnumerable<TypeAnalysisContext> methodGenericParameters)
330
    {
331
        if (this is ConcreteGenericMethodAnalysisContext)
×
332
        {
333
            throw new InvalidOperationException($"Attempted to make a {nameof(ConcreteGenericMethodAnalysisContext)} concrete: {this}");
×
334
        }
335
        else
336
        {
337
            return new ConcreteGenericMethodAnalysisContext(this, typeGenericParameters, methodGenericParameters);
×
338
        }
339
    }
340

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

343
    #region StableNameDot implementation
344

345
    ITypeInfoProvider IMethodInfoProvider.ReturnType =>
346
        Definition!.RawReturnType!.ThisOrElementIsGenericParam()
×
347
            ? new GenericParameterTypeInfoProviderWrapper(Definition.RawReturnType!.GetGenericParamName())
×
348
            : TypeAnalysisContext.GetSndnProviderForType(AppContext, Definition!.RawReturnType);
×
349

350
    IEnumerable<IParameterInfoProvider> IMethodInfoProvider.ParameterInfoProviders => Parameters;
×
351

352
    string IMethodInfoProvider.MethodName => Name;
×
353

354
    MethodAttributes IMethodInfoProvider.MethodAttributes => Attributes;
×
355

356
    MethodSemantics IMethodInfoProvider.MethodSemantics
357
    {
358
        get
359
        {
360
            if (DeclaringType != null)
×
361
            {
362
                //This one is a bit trickier, as il2cpp doesn't use semantics.
363
                foreach (var prop in DeclaringType.Properties)
×
364
                {
365
                    if (prop.Getter == this)
×
366
                        return MethodSemantics.Getter;
×
367
                    if (prop.Setter == this)
×
368
                        return MethodSemantics.Setter;
×
369
                }
370

371
                foreach (var evt in DeclaringType.Events)
×
372
                {
373
                    if (evt.Adder == this)
×
374
                        return MethodSemantics.AddOn;
×
375
                    if (evt.Remover == this)
×
376
                        return MethodSemantics.RemoveOn;
×
377
                    if (evt.Invoker == this)
×
378
                        return MethodSemantics.Fire;
×
379
                }
380
            }
381

382
            return 0;
×
383
        }
×
384
    }
385

386
    #endregion
387
}
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