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

SamboyCoding / Cpp2IL / 20487925661

24 Dec 2025 02:11PM UTC coverage: 34.275% (-0.04%) from 34.31%
20487925661

push

github

SamboyCoding
Other properties too

This also makes ParameterAnalysisContext::ParameterType not virtual

1791 of 6588 branches covered (27.19%)

Branch coverage included in aggregate %.

10 of 20 new or added lines in 7 files covered. (50.0%)

129 existing lines in 7 files now uncovered.

4191 of 10865 relevant lines covered (38.57%)

180313.71 hits per line

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

53.62
/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
82
    {
83
        get => OverrideAttributes ?? DefaultAttributes;
261,415!
UNCOV
84
        set => OverrideAttributes = value;
×
85
    }
86

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

89
    public virtual MethodImplAttributes? OverrideImplAttributes { get; set; }
87,030✔
90

91
    public MethodImplAttributes ImplAttributes
92
    {
93
        get => OverrideImplAttributes ?? DefaultImplAttributes;
87,030!
UNCOV
94
        set => OverrideImplAttributes = value;
×
95
    }
96

97
    public MethodAttributes Visibility
98
    {
99
        get
100
        {
UNCOV
101
            return Attributes & MethodAttributes.MemberAccessMask;
×
102
        }
103
        set
104
        {
UNCOV
105
            Attributes = (Attributes & ~MethodAttributes.MemberAccessMask) | (value & MethodAttributes.MemberAccessMask);
×
UNCOV
106
        }
×
107
    }
108

109
    private List<GenericParameterTypeAnalysisContext>? _genericParameters;
110
    public override List<GenericParameterTypeAnalysisContext> GenericParameters
111
    {
112
        get
113
        {
114
            // Lazy load the generic parameters
115
            _genericParameters ??= Definition?.GenericContainer?.GenericParameters.Select(p => new GenericParameterTypeAnalysisContext(p, this)).ToList() ?? [];
478,429!
116
            return _genericParameters;
473,408✔
117
        }
118
    }
119

120
    private ushort Slot => Definition?.slot ?? ushort.MaxValue;
75,705!
121

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

124
    public TypeAnalysisContext? OverrideReturnType { get; set; }
385,996✔
125

126
    //TODO Support custom attributes on return types (v31 feature)
127
    public TypeAnalysisContext ReturnType
128
    {
129
        get => OverrideReturnType ?? DefaultReturnType;
385,996✔
NEW
130
        set => OverrideReturnType = value;
×
131
    }
132
    
133
    protected Memory<byte>? rawMethodBody;
134

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

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

147
            var declaringTypeDefinition = DeclaringType?.Definition;
18,047!
148
            if (declaringTypeDefinition == null)
18,047!
UNCOV
149
                return [];
×
150

151
            var vtable = declaringTypeDefinition.VTable;
18,047✔
152
            if (vtable == null)
18,047!
UNCOV
153
                return [];
×
154

155
            return GetOverriddenMethods(declaringTypeDefinition, vtable);
18,047✔
156

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

178
                method = null;
10,360✔
179
                return false;
10,360✔
180
            }
181

182
            IEnumerable<MethodAnalysisContext> GetOverriddenMethods(Il2CppTypeDefinition declaringTypeDefinition, MetadataUsage?[] vtable)
183
            {
184
                for (var i = 0; i < vtable.Length; ++i)
683,696✔
185
                {
186
                    var vtableEntry = vtable[i];
323,803✔
187
                    if (vtableEntry is null or { Type: not MetadataUsageType.MethodDef })
323,803✔
188
                        continue;
189

190
                    if (vtableEntry.AsMethod() != Definition)
318,193✔
191
                        continue;
192

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

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

UNCOV
222
    private static readonly List<IBlockProcessor> blockProcessors =
×
UNCOV
223
    [
×
UNCOV
224
        new MetadataProcessor(),
×
UNCOV
225
        new CallProcessor()
×
UNCOV
226
    ];
×
227

228
    public MethodAnalysisContext(Il2CppMethodDefinition? definition, TypeAnalysisContext parent) : base(definition?.token ?? 0, parent.AppContext)
738,870✔
229
    {
230
        DeclaringType = parent;
738,870✔
231
        Definition = definition;
738,870✔
232

233
        if (Definition != null)
738,870✔
234
        {
235
            InitCustomAttributeData();
439,980✔
236

237
            for (var i = 0; i < Definition.InternalParameterData!.Length; i++)
1,890,450✔
238
            {
239
                var parameterDefinition = Definition.InternalParameterData![i];
505,245✔
240
                Parameters.Add(new(parameterDefinition, i, this));
505,245✔
241
            }
242
        }
243
        else
244
            rawMethodBody = Array.Empty<byte>();
298,890✔
245
    }
298,890✔
246

247
    [MemberNotNull(nameof(rawMethodBody))]
248
    public void EnsureRawBytes()
249
    {
250
        rawMethodBody ??= InitRawBytes();
439,980✔
251
    }
439,980✔
252

253
    private Memory<byte> InitRawBytes()
254
    {
255
        //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.
256
        //E.g. UnityEngine.Purchasing.AppleCore.dll: UnityEngine.Purchasing.INativeAppleStore::SetUnityPurchasingCallback on among us (itch.io build)
257
        if (Definition != null && Definition.MethodPointer != 0 && !Definition.Attributes.HasFlag(MethodAttributes.Abstract))
439,980✔
258
        {
259
            var ret = AppContext.InstructionSet.GetRawBytesForMethod(this, false);
425,868✔
260

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

266
            return ret;
425,868✔
267
        }
268
        else
269
            return Array.Empty<byte>();
14,112✔
270
    }
271

272
    protected MethodAnalysisContext(ApplicationAnalysisContext context) : base(0, context)
×
273
    {
UNCOV
274
        rawMethodBody = Array.Empty<byte>();
×
275
    }
×
276

277
    [MemberNotNull(nameof(ConvertedIsil))]
278
    public void Analyze()
279
    {
UNCOV
280
        if (ConvertedIsil != null)
×
281
            return;
×
282

283
        if (UnderlyingPointer == 0)
×
284
        {
UNCOV
285
            ConvertedIsil = [];
×
286
            return;
×
287
        }
288

UNCOV
289
        ConvertedIsil = AppContext.InstructionSet.GetIsilFromMethod(this);
×
290

UNCOV
291
        if (ConvertedIsil.Count == 0)
×
292
            return; //Nothing to do, empty function
×
293

294
        ControlFlowGraph = new ISILControlFlowGraph();
×
UNCOV
295
        ControlFlowGraph.Build(ConvertedIsil);
×
296

297
        // Post step to convert metadata usage. Ldstr Opcodes etc.
UNCOV
298
        foreach (var block in ControlFlowGraph.Blocks)
×
299
        {
UNCOV
300
            foreach (var converter in blockProcessors)
×
301
            {
302
                converter.Process(this, block);
×
303
            }
304
        }
UNCOV
305
    }
×
306

307
    public void ReleaseAnalysisData()
308
    {
309
        ConvertedIsil = null;
×
UNCOV
310
        ControlFlowGraph = null;
×
UNCOV
311
    }
×
312

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

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

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

339
    #region StableNameDot implementation
340

341
    ITypeInfoProvider IMethodInfoProvider.ReturnType =>
342
        Definition!.RawReturnType!.ThisOrElementIsGenericParam()
×
UNCOV
343
            ? new GenericParameterTypeInfoProviderWrapper(Definition.RawReturnType!.GetGenericParamName())
×
UNCOV
344
            : TypeAnalysisContext.GetSndnProviderForType(AppContext, Definition!.RawReturnType);
×
345

UNCOV
346
    IEnumerable<IParameterInfoProvider> IMethodInfoProvider.ParameterInfoProviders => Parameters;
×
347

348
    string IMethodInfoProvider.MethodName => Name;
×
349

UNCOV
350
    MethodAttributes IMethodInfoProvider.MethodAttributes => Attributes;
×
351

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

UNCOV
367
                foreach (var evt in DeclaringType.Events)
×
368
                {
UNCOV
369
                    if (evt.Adder == this)
×
370
                        return MethodSemantics.AddOn;
×
371
                    if (evt.Remover == this)
×
UNCOV
372
                        return MethodSemantics.RemoveOn;
×
UNCOV
373
                    if (evt.Invoker == this)
×
UNCOV
374
                        return MethodSemantics.Fire;
×
375
                }
376
            }
377

UNCOV
378
            return 0;
×
UNCOV
379
        }
×
380
    }
381

382
    #endregion
383
}
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