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

SamboyCoding / Cpp2IL / 17684316232

12 Sep 2025 07:36PM UTC coverage: 34.302% (-0.02%) from 34.326%
17684316232

push

github

web-flow
Add some additional methods for working with concrete generics (#485)

1791 of 6592 branches covered (27.17%)

Branch coverage included in aggregate %.

0 of 8 new or added lines in 3 files covered. (0.0%)

1 existing line in 1 file now uncovered.

4191 of 10847 relevant lines covered (38.64%)

180612.93 hits per line

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

54.21
/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>
61
    public bool IsVoid => ReturnType == AppContext.SystemTypes.SystemVoidType;
×
62

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

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

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

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

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

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

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

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

79
    public virtual MethodAttributes? OverrideAttributes { get; set; }
261,415✔
80

81
    public MethodAttributes Attributes => OverrideAttributes ?? DefaultAttributes;
261,415!
82

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

85
    public virtual MethodImplAttributes? OverrideImplAttributes { get; set; }
87,030✔
86

87
    public MethodImplAttributes ImplAttributes => OverrideImplAttributes ?? DefaultImplAttributes;
87,030!
88

89
    public MethodAttributes Visibility
90
    {
91
        get
92
        {
93
            return Attributes & MethodAttributes.MemberAccessMask;
×
94
        }
95
        set
96
        {
97
            OverrideAttributes = (Attributes & ~MethodAttributes.MemberAccessMask) | (value & MethodAttributes.MemberAccessMask);
×
98
        }
×
99
    }
100

101
    private List<GenericParameterTypeAnalysisContext>? _genericParameters;
102
    public override List<GenericParameterTypeAnalysisContext> GenericParameters
103
    {
104
        get
105
        {
106
            // Lazy load the generic parameters
107
            _genericParameters ??= Definition?.GenericContainer?.GenericParameters.Select(p => new GenericParameterTypeAnalysisContext(p, this)).ToList() ?? [];
478,429!
108
            return _genericParameters;
473,408✔
109
        }
110
    }
111

112
    private ushort Slot => Definition?.slot ?? ushort.MaxValue;
75,705!
113

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

116
    public TypeAnalysisContext? OverrideReturnType { get; set; }
385,996✔
117

118
    //TODO Support custom attributes on return types (v31 feature)
119
    public TypeAnalysisContext ReturnType => OverrideReturnType ?? DefaultReturnType;
385,996✔
120
    
121
    protected Memory<byte>? rawMethodBody;
122

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

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

135
            var declaringTypeDefinition = DeclaringType?.Definition;
18,047!
136
            if (declaringTypeDefinition == null)
18,047!
137
                return [];
×
138

139
            var vtable = declaringTypeDefinition.VTable;
18,047✔
140
            if (vtable == null)
18,047!
141
                return [];
×
142

143
            return GetOverriddenMethods(declaringTypeDefinition, vtable);
18,047✔
144

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

166
                method = null;
10,360✔
167
                return false;
10,360✔
168
            }
169

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

178
                    if (vtableEntry.AsMethod() != Definition)
318,193✔
179
                        continue;
180

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

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

210
    private static readonly List<IBlockProcessor> blockProcessors =
×
211
    [
×
212
        new MetadataProcessor(),
×
213
        new CallProcessor()
×
214
    ];
×
215

216
    public MethodAnalysisContext(Il2CppMethodDefinition? definition, TypeAnalysisContext parent) : base(definition?.token ?? 0, parent.AppContext)
738,870✔
217
    {
218
        DeclaringType = parent;
738,870✔
219
        Definition = definition;
738,870✔
220

221
        if (Definition != null)
738,870✔
222
        {
223
            InitCustomAttributeData();
439,980✔
224

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

235
    [MemberNotNull(nameof(rawMethodBody))]
236
    public void EnsureRawBytes()
237
    {
238
        rawMethodBody ??= InitRawBytes();
439,980✔
239
    }
439,980✔
240

241
    private Memory<byte> InitRawBytes()
242
    {
243
        //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.
244
        //E.g. UnityEngine.Purchasing.AppleCore.dll: UnityEngine.Purchasing.INativeAppleStore::SetUnityPurchasingCallback on among us (itch.io build)
245
        if (Definition != null && Definition.MethodPointer != 0 && !Definition.Attributes.HasFlag(MethodAttributes.Abstract))
439,980✔
246
        {
247
            var ret = AppContext.InstructionSet.GetRawBytesForMethod(this, false);
425,868✔
248

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

254
            return ret;
425,868✔
255
        }
256
        else
257
            return Array.Empty<byte>();
14,112✔
258
    }
259

260
    protected MethodAnalysisContext(ApplicationAnalysisContext context) : base(0, context)
×
261
    {
262
        rawMethodBody = Array.Empty<byte>();
×
263
    }
×
264

265
    [MemberNotNull(nameof(ConvertedIsil))]
266
    public void Analyze()
267
    {
268
        if (ConvertedIsil != null)
×
269
            return;
×
270

271
        if (UnderlyingPointer == 0)
×
272
        {
273
            ConvertedIsil = [];
×
274
            return;
×
275
        }
276

277
        ConvertedIsil = AppContext.InstructionSet.GetIsilFromMethod(this);
×
278

279
        if (ConvertedIsil.Count == 0)
×
280
            return; //Nothing to do, empty function
×
281

282
        ControlFlowGraph = new ISILControlFlowGraph();
×
283
        ControlFlowGraph.Build(ConvertedIsil);
×
284

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

295
    public void ReleaseAnalysisData()
296
    {
297
        ConvertedIsil = null;
×
298
        ControlFlowGraph = null;
×
299
    }
×
300

301
    public ConcreteGenericMethodAnalysisContext MakeGenericInstanceMethod(params IEnumerable<TypeAnalysisContext> methodGenericParameters)
302
    {
303
        if (this is ConcreteGenericMethodAnalysisContext methodOnGenericInstanceType)
×
304
        {
305
            return new ConcreteGenericMethodAnalysisContext(methodOnGenericInstanceType.BaseMethodContext, methodOnGenericInstanceType.TypeGenericParameters, methodGenericParameters);
×
306
        }
307
        else
308
        {
309
            return new ConcreteGenericMethodAnalysisContext(this, [], methodGenericParameters);
×
310
        }
311
    }
312

313
    public ConcreteGenericMethodAnalysisContext MakeConcreteGenericMethod(IEnumerable<TypeAnalysisContext> typeGenericParameters, IEnumerable<TypeAnalysisContext> methodGenericParameters)
314
    {
NEW
315
        if (this is ConcreteGenericMethodAnalysisContext)
×
316
        {
NEW
317
            throw new InvalidOperationException($"Attempted to make a {nameof(ConcreteGenericMethodAnalysisContext)} concrete: {this}");
×
318
        }
319
        else
320
        {
NEW
321
            return new ConcreteGenericMethodAnalysisContext(this, typeGenericParameters, methodGenericParameters);
×
322
        }
323
    }
324

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

327
    #region StableNameDot implementation
328

329
    ITypeInfoProvider IMethodInfoProvider.ReturnType =>
330
        Definition!.RawReturnType!.ThisOrElementIsGenericParam()
×
331
            ? new GenericParameterTypeInfoProviderWrapper(Definition.RawReturnType!.GetGenericParamName())
×
332
            : TypeAnalysisContext.GetSndnProviderForType(AppContext, Definition!.RawReturnType);
×
333

334
    IEnumerable<IParameterInfoProvider> IMethodInfoProvider.ParameterInfoProviders => Parameters;
×
335

336
    string IMethodInfoProvider.MethodName => Name;
×
337

338
    MethodAttributes IMethodInfoProvider.MethodAttributes => Attributes;
×
339

340
    MethodSemantics IMethodInfoProvider.MethodSemantics
341
    {
342
        get
343
        {
344
            if (DeclaringType != null)
×
345
            {
346
                //This one is a bit trickier, as il2cpp doesn't use semantics.
347
                foreach (var prop in DeclaringType.Properties)
×
348
                {
349
                    if (prop.Getter == this)
×
350
                        return MethodSemantics.Getter;
×
351
                    if (prop.Setter == this)
×
352
                        return MethodSemantics.Setter;
×
353
                }
354

355
                foreach (var evt in DeclaringType.Events)
×
356
                {
357
                    if (evt.Adder == this)
×
358
                        return MethodSemantics.AddOn;
×
359
                    if (evt.Remover == this)
×
360
                        return MethodSemantics.RemoveOn;
×
361
                    if (evt.Invoker == this)
×
362
                        return MethodSemantics.Fire;
×
363
                }
364
            }
365

366
            return 0;
×
367
        }
×
368
    }
369

370
    #endregion
371
}
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