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

SamboyCoding / Cpp2IL / 18664957279

20 Oct 2025 09:07PM UTC coverage: 34.295% (-0.02%) from 34.31%
18664957279

Pull #491

github

web-flow
Merge c3be0c866 into e66a74bb3
Pull Request #491: Add set accessor for Attributes properties

1791 of 6588 branches covered (27.19%)

Branch coverage included in aggregate %.

8 of 19 new or added lines in 7 files covered. (42.11%)

124 existing lines in 6 files now uncovered.

4191 of 10855 relevant lines covered (38.61%)

180479.82 hits per line

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

53.82
/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!
NEW
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!
NEW
94
        set => OverrideImplAttributes = value;
×
95
    }
96

97
    public MethodAttributes Visibility
98
    {
99
        get
100
        {
101
            return Attributes & MethodAttributes.MemberAccessMask;
×
102
        }
103
        set
104
        {
NEW
105
            Attributes = (Attributes & ~MethodAttributes.MemberAccessMask) | (value & MethodAttributes.MemberAccessMask);
×
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 => OverrideReturnType ?? DefaultReturnType;
385,996✔
128
    
129
    protected Memory<byte>? rawMethodBody;
130

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

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

143
            var declaringTypeDefinition = DeclaringType?.Definition;
18,047!
144
            if (declaringTypeDefinition == null)
18,047!
145
                return [];
×
146

147
            var vtable = declaringTypeDefinition.VTable;
18,047✔
148
            if (vtable == null)
18,047!
149
                return [];
×
150

151
            return GetOverriddenMethods(declaringTypeDefinition, vtable);
18,047✔
152

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

174
                method = null;
10,360✔
175
                return false;
10,360✔
176
            }
177

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

186
                    if (vtableEntry.AsMethod() != Definition)
318,193✔
187
                        continue;
188

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

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

UNCOV
218
    private static readonly List<IBlockProcessor> blockProcessors =
×
UNCOV
219
    [
×
UNCOV
220
        new MetadataProcessor(),
×
UNCOV
221
        new CallProcessor()
×
222
    ];
×
223

224
    public MethodAnalysisContext(Il2CppMethodDefinition? definition, TypeAnalysisContext parent) : base(definition?.token ?? 0, parent.AppContext)
738,870✔
225
    {
226
        DeclaringType = parent;
738,870✔
227
        Definition = definition;
738,870✔
228

229
        if (Definition != null)
738,870✔
230
        {
231
            InitCustomAttributeData();
439,980✔
232

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

243
    [MemberNotNull(nameof(rawMethodBody))]
244
    public void EnsureRawBytes()
245
    {
246
        rawMethodBody ??= InitRawBytes();
439,980✔
247
    }
439,980✔
248

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

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

262
            return ret;
425,868✔
263
        }
264
        else
265
            return Array.Empty<byte>();
14,112✔
266
    }
267

UNCOV
268
    protected MethodAnalysisContext(ApplicationAnalysisContext context) : base(0, context)
×
269
    {
UNCOV
270
        rawMethodBody = Array.Empty<byte>();
×
UNCOV
271
    }
×
272

273
    [MemberNotNull(nameof(ConvertedIsil))]
274
    public void Analyze()
275
    {
UNCOV
276
        if (ConvertedIsil != null)
×
UNCOV
277
            return;
×
278

UNCOV
279
        if (UnderlyingPointer == 0)
×
280
        {
281
            ConvertedIsil = [];
×
UNCOV
282
            return;
×
283
        }
284

285
        ConvertedIsil = AppContext.InstructionSet.GetIsilFromMethod(this);
×
286

UNCOV
287
        if (ConvertedIsil.Count == 0)
×
UNCOV
288
            return; //Nothing to do, empty function
×
289

UNCOV
290
        ControlFlowGraph = new ISILControlFlowGraph();
×
291
        ControlFlowGraph.Build(ConvertedIsil);
×
292

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

303
    public void ReleaseAnalysisData()
304
    {
305
        ConvertedIsil = null;
×
UNCOV
306
        ControlFlowGraph = null;
×
UNCOV
307
    }
×
308

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

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

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

335
    #region StableNameDot implementation
336

337
    ITypeInfoProvider IMethodInfoProvider.ReturnType =>
UNCOV
338
        Definition!.RawReturnType!.ThisOrElementIsGenericParam()
×
UNCOV
339
            ? new GenericParameterTypeInfoProviderWrapper(Definition.RawReturnType!.GetGenericParamName())
×
UNCOV
340
            : TypeAnalysisContext.GetSndnProviderForType(AppContext, Definition!.RawReturnType);
×
341

342
    IEnumerable<IParameterInfoProvider> IMethodInfoProvider.ParameterInfoProviders => Parameters;
×
343

344
    string IMethodInfoProvider.MethodName => Name;
×
345

346
    MethodAttributes IMethodInfoProvider.MethodAttributes => Attributes;
×
347

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

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

374
            return 0;
×
UNCOV
375
        }
×
376
    }
377

378
    #endregion
379
}
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