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

SamboyCoding / Cpp2IL / 30750912933

02 Aug 2026 01:53PM UTC coverage: 36.374% (-0.008%) from 36.382%
30750912933

Pull #593

github

web-flow
Merge 4dbcc591e into a87d484b9
Pull Request #593: Analysis: Handle GenericInstanceTypeAnalysisContext comparisons when resolving calls

2857 of 8967 branches covered (31.86%)

Branch coverage included in aggregate %.

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

5293 of 13439 relevant lines covered (39.39%)

164501.17 hits per line

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

0.0
/Cpp2IL.Core/Analysis/MetadataResolver.cs
1
using System.Collections.Generic;
2
using System.Linq;
3
using Cpp2IL.Core.Extensions;
4
using Cpp2IL.Core.Graphs;
5
using Cpp2IL.Core.Il2CppApiFunctions;
6
using Cpp2IL.Core.ISIL;
7
using Cpp2IL.Core.Model.Contexts;
8
using Cpp2IL.Core.Utils;
9
using LibCpp2IL;
10

11
namespace Cpp2IL.Core.Analysis;
12

13
public static class MetadataResolver
14
{
15
    public static void ResolveAll(MethodAnalysisContext method)
16
    {
17
        ResolveCalls(method);
×
18
        ResolveGetter(method);
×
19
        ResolveMetadataUsages(method);
×
20
    }
×
21

22
    /// <summary>
23
    /// Resolves <c>Move local, [absoluteAddress]</c> loads of IL2CPP metadata-usage globals into a
24
    /// strongly-typed operand: a string literal, a <see cref="TypeAnalysisContext"/> (an Il2CppType*/
25
    /// Il2CppClass* usage) or, for a MethodInfo* usage, a <see cref="RuntimeMethodInfoAnalysisContext"/>
26
    /// naming the method it refers to (also used to type the local - see <see cref="LocalVariables"/>).
27
    /// </summary>
28
    private static void ResolveMetadataUsages(MethodAnalysisContext method)
29
    {
30
        var libContext = method.AppContext.LibCpp2IlContext;
×
31

32
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
33
        {
34
            if (instruction.OpCode != OpCode.Move)
×
35
                continue;
36

37
            // Only an absolute-address load [addr] (no base/index/scale) can be a metadata-usage global.
38
            if (instruction.Operands[0] is not LocalVariable
×
39
                || instruction.Operands[1] is not MemoryOperand { Base: null, Index: null, Scale: 0 } memory)
×
40
                continue;
41

42
            var address = (ulong)memory.Addend;
×
43

44
            // String literal.
45
            var stringLiteral = libContext.GetLiteralByAddress(address);
×
46
            if (stringLiteral != null)
×
47
            {
48
                instruction.SetOperand(1, new StringLiteral(stringLiteral));
×
49
                continue;
×
50
            }
51

52
            // Type metadata usage (Il2CppType* / Il2CppClass*).
53
            if (method.DeclaringType is { } declaringType)
×
54
            {
55
                var typeGlobal = libContext.GetTypeGlobalByAddress(address);
×
56
                if (typeGlobal != null)
×
57
                {
58
                    instruction.SetOperand(1, declaringType.AppContext.ResolveIl2CppType(typeGlobal));
×
59
                    continue;
×
60
                }
61
            }
62

63
            // Method metadata usage (MethodInfo*). On metadata v27+ GetMethodGlobalByAddress can return
64
            // any global, so confirm it is actually a method before resolving - the resolver's switch
65
            // throws on other usage kinds.
66
            var methodUsage = libContext.GetMethodGlobalByAddress(address);
×
67
            if (methodUsage?.Type is MetadataUsageType.MethodDef or MetadataUsageType.MethodRef
×
68
                && method.AppContext.ResolveContextForMethod(methodUsage) is { DeclaringType: { } methodDeclaringType } methodContext)
×
69
                instruction.SetOperand(1, new RuntimeMethodInfoAnalysisContext(methodContext, methodDeclaringType.DeclaringAssembly));
×
70
        }
71
    }
×
72

73
    /// <summary>
74
    /// Replaces every <c>[base + addend]</c> memory operand whose base is a typed local with a
75
    /// <see cref="FieldReference"/> to the field at that offset. Returns whether any operand was
76
    /// resolved this pass, so the type/field fixpoint can detect convergence: as more bases become
77
    /// typed (a field load types its result, which is the base of the next load), more offsets
78
    /// resolve, so this is re-run until it stops finding new fields.
79
    /// </summary>
80
    public static bool ResolveFieldOffsets(MethodAnalysisContext method)
81
    {
82
        var changed = false;
×
83

84
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
85
        {
86
            for (var i = 0; i < instruction.Operands.Count; i++)
×
87
            {
88
                var operand = instruction.Operands[i];
×
89

90
                if (operand is not MemoryOperand memory)
×
91
                    continue;
92

93
                // Has to be [base (local) + addend (field offset)]
94
                if (memory.Index != null || memory.Scale != 0)
×
95
                    continue;
96

97
                if (memory.Base is not LocalVariable local || local?.Type == null)
×
98
                    continue;
99

100
                // check if static field access
101
                var staticOwner = (local.Type as StaticFieldStorageTypeAnalysisContext)?.OwnerType;
×
102

103
                // a generic instance keeps its members on the definition, so look there for the statics.
104
                var candidates = staticOwner == null
×
105
                    ? local.Type.Fields
×
106
                    : ((staticOwner as GenericInstanceTypeAnalysisContext)?.GenericType ?? staticOwner).Fields;
×
107

108
                var field = candidates.FirstOrDefault(f => f.IsStatic == (staticOwner != null) && f.BackingData?.FieldOffset == memory.Addend);
×
109

110
                if (field == null) // TODO: Support nested fields (Field1.Field2.Field3)
×
111
                    continue;
112

113
                // make sure we have a full GIT for ldsfld. open type is bad.
114
                if (staticOwner is GenericInstanceTypeAnalysisContext genericOwner)
×
115
                    field = new ConcreteGenericFieldAnalysisContext(field, genericOwner);
×
116

117
                instruction.SetOperand(i, new FieldReference(field, local, (int)memory.Addend));
×
118
                changed = true;
×
119
            }
120
        }
121

122
        return changed;
×
123
    }
124

125
    private static void ResolveCalls(MethodAnalysisContext method)
126
    {
127
        foreach (var block in method.ControlFlowGraph!.Blocks)
×
128
        {
129
            if (block.BlockType != BlockType.Call && block.BlockType != BlockType.TailCall)
×
130
                continue;
131

132
            var callInstruction = block.Instructions[^1];
×
133
            if (callInstruction.Operands[0] is not Immediate dest)
×
134
                continue;
135

136
            var target = dest.UnsignedValue;
×
137

138
            var keyFunctionAddresses = method.AppContext.GetOrCreateKeyFunctionAddresses();
×
139

140
            if (keyFunctionAddresses.IsKeyFunctionAddress(target))
×
141
            {
142
                HandleKeyFunction(method.AppContext, callInstruction, target, keyFunctionAddresses);
×
143
                continue;
×
144
            }
145

146
            //Non-key function call. Try to find a single match
147
            if (!method.AppContext.MethodsByAddress.TryGetValue(target, out var targetMethods))
×
148
            {
149
                // Not a managed method at all. It may be one of the runtime helpers that exist purely to
150
                // throw, in which case restore the throw itself
151
                if (ThrowHelperRecovery.GetThrownException(method.AppContext, target) is { } thrown)
×
152
                {
153
                    callInstruction.OpCode = OpCode.Throw;
×
154
                    callInstruction.SetOperands(thrown);
×
155
                }
156

157
                continue;
×
158
            }
159

160
            // Duplicated/Shared method bodies are resolved later in ResolveCallsViaMethodInfo/ResolveAmbiguousCalls.
161
            if (targetMethods is not [{ } singleTargetMethod])
×
162
                continue;
163

164
            callInstruction.SetOperand(0, singleTargetMethod);
×
165
        }
166

167
        method.ControlFlowGraph.MergeCallBlocks();
×
168
    }
×
169

170
    /// <summary>
171
    /// Resolves calls whose address maps to more than one method by matching the receiver's known
172
    /// type against the candidates' declaring types. Runs inside the type/field fixpoint and so
173
    /// re-fires as receivers become typed - a resolved call types its return value, which can type
174
    /// the receiver of a further call. Returns whether any call was resolved this pass.
175
    ///
176
    /// Conservative by design: it commits only when exactly one non-static candidate's declaring
177
    /// type matches the receiver's type. Anything still untyped or ambiguous is left for a later
178
    /// pass, or left unresolved - it never guesses.
179
    /// </summary>
180
    public static bool ResolveAmbiguousCalls(MethodAnalysisContext method)
181
    {
182
        var changed = false;
×
183

184
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
185
        {
186
            if (!instruction.IsCall)
×
187
                continue;
188

189
            // A resolved call's target is a method/key-function name; only unresolved ones are still numeric.
190
            if (instruction.Operands[0] is not Immediate target)
×
191
                continue;
192

193
            if (!method.AppContext.MethodsByAddress.TryGetValue(target.UnsignedValue, out var candidates) || candidates.Count < 2)
×
194
                continue;
195

196
            if (GetReceiver(instruction) is not { Type: { } receiverType })
×
197
                continue;
198

199
            MethodAnalysisContext? match = null;
×
200
            var ambiguous = false;
×
201

202
            foreach (var candidate in candidates)
×
203
            {
NEW
204
                if (candidate.IsStatic || !MiscUtils.DescribesSameThing(candidate.DeclaringType, receiverType))
×
205
                    continue;
206

207
                if (match != null)
×
208
                {
209
                    ambiguous = true;
×
210
                    break;
×
211
                }
212

213
                match = candidate;
×
214
            }
215

216
            if (ambiguous || match == null)
×
217
                continue;
218

219
            instruction.SetOperand(0, match);
×
220
            changed = true;
×
221
        }
222

223
        return changed;
×
224
    }
225

226
    // The receiver ('this') of a call is the first integer-slot argument: operand 1 for CallVoid
227
    // (after the target), operand 2 for Call (after the target and the return value).
228
    private static LocalVariable? GetReceiver(Instruction call)
229
    {
230
        var index = call.OpCode == OpCode.CallVoid ? 1 : 2;
×
231
        return index < call.Operands.Count ? call.Operands[index] as LocalVariable : null;
×
232
    }
233

234
    /// <summary>
235
    /// Resolves any Call (theoretically should always be a CallVoid) target directly after a Newobj to a constructor call.
236
    /// </summary>
237
    public static bool ResolveConstructorCalls(MethodAnalysisContext method)
238
    {
239
        var definitions = new Dictionary<LocalVariable, Instruction>();
×
240
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
241
            if (instruction.Destination is LocalVariable definition)
×
242
                definitions[definition] = instruction;
×
243

244
        var changed = false;
×
245

246
        foreach (var instruction in method.ControlFlowGraph.Instructions)
×
247
        {
248
            if (!instruction.IsCall || instruction.Operands[0] is not Immediate callTarget)
×
249
                continue;
250

251
            if (!method.AppContext.MethodsByAddress.TryGetValue(callTarget.UnsignedValue, out var candidates))
×
252
                continue;
253

254
            if (GetReceiver(instruction) is not { } receiver || AllocatedType(receiver, definitions) is not { } allocatedType)
×
255
                continue;
256

NEW
257
            var constructor = candidates.FirstOrDefault(c => !c.IsStatic && c.Name == ".ctor" && MiscUtils.DescribesSameThing(c.DeclaringType, allocatedType));
×
258
            if (constructor == null)
×
259
                continue;
260

261
            instruction.SetOperand(0, constructor);
×
262
            changed = true;
×
263
        }
264

265
        return changed;
×
266
    }
267

268
    // Follow SSA copies from a local back to the Newobj that produced the value
269
    private static TypeAnalysisContext? AllocatedType(LocalVariable local, Dictionary<LocalVariable, Instruction> definitions)
270
    {
271
        var visited = new HashSet<LocalVariable>();
×
272

273
        while (visited.Add(local) && definitions.TryGetValue(local, out var definition))
×
274
        {
275
            switch (definition.OpCode)
×
276
            {
277
                case OpCode.Newobj:
278
                    return (definition.Operands[0] as LocalVariable)?.Type;
×
279
                case OpCode.Move when definition.Operands[1] is LocalVariable source:
×
280
                    local = source;
×
281
                    continue;
×
282
            }
283

284
            break;
285
        }
286

287
        return null;
×
288
    }
289

290
    /// <summary>
291
    /// Resolves calls whose address maps to more than one method by reading the runtime
292
    /// <c>MethodInfo*</c> the caller passes in, if there is one.
293
    /// </summary>
294
    public static bool ResolveCallsViaMethodInfo(MethodAnalysisContext method)
295
    {
296
        var changed = false;
×
297

298
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
299
        {
300
            if (!instruction.IsCall)
×
301
                continue;
302

303
            if (instruction.Operands[0] is not Immediate target)
×
304
                //Already resolved
305
                continue;
306

307
            if (!method.AppContext.MethodsByAddress.TryGetValue(target.UnsignedValue, out var candidates) || candidates.Count < 2)
×
308
                //Not a managed method at all
309
                continue;
310

311
            if (GetMethodInfoArgument(instruction) is not { RepresentedMethod: { } representedMethod })
×
312
                //No MethodInfo to work with
313
                continue;
314

315
            //Try to actually match on the method name so we don't just replace a call with something else.
316
            var representedBase = BaseMethodOf(representedMethod);
×
317
            if (!candidates.Any(candidate => ReferenceEquals(BaseMethodOf(candidate), representedBase)))
×
318
                continue;
319

320
            instruction.SetOperand(0, representedMethod);
×
321
            changed = true;
×
322
        }
323

324
        return changed;
×
325
    }
326

327
    private static MethodAnalysisContext BaseMethodOf(MethodAnalysisContext method) =>
328
        method is ConcreteGenericMethodAnalysisContext { BaseMethodContext: { } baseMethod } ? baseMethod : method;
×
329

330
    private static RuntimeMethodInfoAnalysisContext? GetMethodInfoArgument(Instruction call)
331
    {
332
        var firstArg = call.OpCode == OpCode.CallVoid ? 1 : 2;
×
333

334
        for (var i = call.Operands.Count - 1; i >= firstArg; i--)
×
335
        {
336
            switch (call.Operands[i])
×
337
            {
338
                case RuntimeMethodInfoAnalysisContext methodInfo:
339
                    return methodInfo;
×
340
                case LocalVariable { Type: RuntimeMethodInfoAnalysisContext methodInfoLocal }:
341
                    return methodInfoLocal;
×
342
            }
343
        }
344

345
        return null;
×
346
    }
347

348
    private static void HandleKeyFunction(ApplicationAnalysisContext appContext, Instruction instruction, ulong target, BaseKeyFunctionAddresses kFA)
349
    {
350
        var method = "";
×
351
        if (target == kFA.il2cpp_codegen_initialize_method || target == kFA.il2cpp_codegen_initialize_runtime_metadata)
×
352
        {
353
            if (appContext.MetadataVersion < 27)
×
354
            {
355
                method = nameof(kFA.il2cpp_codegen_initialize_method);
×
356
            }
357
            else
358
            {
359
                method = nameof(kFA.il2cpp_codegen_initialize_runtime_metadata);
×
360
            }
361
        }
362
        else
363
        {
364
            var pairs = kFA.Pairs.ToList();
×
365
            var key = pairs.FirstOrDefault(pair => pair.Value == target).Key;
×
366
            if (key == null)
×
367
                return;
×
368
            method = key;
×
369
        }
370

371
        if (method != "")
×
372
        {
373
            instruction.SetOperand(0, new StringLiteral(method));
×
374
        }
375
    }
×
376

377
    // Because of il2cpp fields (like cctor_finished_or_no_cctor) [local @ reg+offset] sometimes can't be resolved, but this works for now
378
    private static void ResolveGetter(MethodAnalysisContext method)
379
    {
380
        if (!method.Name.StartsWith("get_"))
×
381
            return;
×
382

383
        // Default get: Return [this @ reg+offset]
384
        var instructions = method.ControlFlowGraph!.Instructions;
×
385
        if (instructions.Count == 1)
×
386
        {
387
            var instr = instructions[0];
×
388

389
            if (instr.OpCode != OpCode.Return
×
390
                || instr.Operands.Count < 1
×
391
                || instr.Operands[0] is not MemoryOperand memory
×
392
                || memory.Index != null || memory.Scale != 0
×
393
                || memory.Base is not LocalVariable local)
×
394
                return;
×
395

396
            var fieldName = $"<{method.Name[4..]}>k__BackingField";
×
397

398
            var field = method.DeclaringType!.Fields.Find(f => f.Name == fieldName);
×
399
            if (field == null)
×
400
                return;
×
401

402
            instr.SetOperand(0, new FieldReference(field, local, (int)memory.Addend));
×
403
        }
404
    }
×
405
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc