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

SamboyCoding / Cpp2IL / 30178263727

25 Jul 2026 10:48PM UTC coverage: 36.302% (-0.8%) from 37.144%
30178263727

push

github

SamboyCoding
Decompiler: Recover static fields, throw helpers, and rgctx, fix bool flags, fix this param in IL, fix float handling somewhat

2890 of 9069 branches covered (31.87%)

Branch coverage included in aggregate %.

28 of 319 new or added lines in 17 files covered. (8.78%)

10 existing lines in 6 files now uncovered.

5291 of 13467 relevant lines covered (39.29%)

164158.62 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.Operands[1] = 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.Operands[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.Operands[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
NEW
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.
NEW
104
                var candidates = staticOwner == null
×
NEW
105
                    ? local.Type.Fields
×
NEW
106
                    : ((staticOwner as GenericInstanceTypeAnalysisContext)?.GenericType ?? staticOwner).Fields;
×
107

NEW
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.
NEW
114
                if (staticOwner is GenericInstanceTypeAnalysisContext genericOwner)
×
NEW
115
                    field = new ConcreteGenericFieldAnalysisContext(field, genericOwner);
×
116

117
                instruction.Operands[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
            var dest = callInstruction.Operands[0];
×
134

135
            if (!dest.IsNumeric())
×
136
                continue;
137

138
            var target = (ulong)dest;
×
139

140
            var keyFunctionAddresses = method.AppContext.GetOrCreateKeyFunctionAddresses();
×
141

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

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

UNCOV
159
                continue;
×
160
            }
161

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

166
            callInstruction.Operands[0] = singleTargetMethod;
×
167
        }
168

169
        method.ControlFlowGraph.MergeCallBlocks();
×
170
    }
×
171

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

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

191
            var target = instruction.Operands[0];
×
192

193
            // A resolved call's target is a method/key-function name; only unresolved ones are still numeric.
194
            if (!target.IsNumeric())
×
195
                continue;
196

197
            if (!method.AppContext.MethodsByAddress.TryGetValue((ulong)target, out var candidates) || candidates.Count < 2)
×
198
                continue;
199

200
            if (GetReceiver(instruction) is not { Type: { } receiverType })
×
201
                continue;
202

203
            MethodAnalysisContext? match = null;
×
204
            var ambiguous = false;
×
205

206
            foreach (var candidate in candidates)
×
207
            {
208
                if (candidate.IsStatic || !ReferenceEquals(candidate.DeclaringType, receiverType))
×
209
                    continue;
210

211
                if (match != null)
×
212
                {
213
                    ambiguous = true;
×
214
                    break;
×
215
                }
216

217
                match = candidate;
×
218
            }
219

220
            if (ambiguous || match == null)
×
221
                continue;
222

223
            instruction.Operands[0] = match;
×
224
            changed = true;
×
225
        }
226

227
        return changed;
×
228
    }
229

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

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

248
        var changed = false;
×
249

250
        foreach (var instruction in method.ControlFlowGraph.Instructions)
×
251
        {
252
            if (!instruction.IsCall || !instruction.Operands[0].IsNumeric())
×
253
                continue;
254

255
            if (!method.AppContext.MethodsByAddress.TryGetValue((ulong)instruction.Operands[0], out var candidates))
×
256
                continue;
257

258
            if (GetReceiver(instruction) is not { } receiver || AllocatedType(receiver, definitions) is not { } allocatedType)
×
259
                continue;
260

261
            var constructor = candidates.FirstOrDefault(c => !c.IsStatic && c.Name == ".ctor" && ReferenceEquals(c.DeclaringType, allocatedType));
×
262
            if (constructor == null)
×
263
                continue;
264

265
            instruction.Operands[0] = constructor;
×
266
            changed = true;
×
267
        }
268

269
        return changed;
×
270
    }
271

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

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

288
            break;
289
        }
290

291
        return null;
×
292
    }
293

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

302
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
303
        {
304
            if (!instruction.IsCall)
×
305
                continue;
306

307
            var target = instruction.Operands[0];
×
308

309
            if (!target.IsNumeric())
×
310
                //Already resolved
311
                continue;
312

313
            if (!method.AppContext.MethodsByAddress.TryGetValue((ulong)target, out var candidates) || candidates.Count < 2)
×
314
                //Not a managed method at all
315
                continue;
316

317
            if (GetMethodInfoArgument(instruction) is not { RepresentedMethod: { } representedMethod })
×
318
                //No MethodInfo to work with
319
                continue;
320

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

326
            instruction.Operands[0] = representedMethod;
×
327
            changed = true;
×
328
        }
329

330
        return changed;
×
331
    }
332

333
    private static MethodAnalysisContext BaseMethodOf(MethodAnalysisContext method) =>
334
        method is ConcreteGenericMethodAnalysisContext { BaseMethodContext: { } baseMethod } ? baseMethod : method;
×
335

336
    private static RuntimeMethodInfoAnalysisContext? GetMethodInfoArgument(Instruction call)
337
    {
338
        var firstArg = call.OpCode == OpCode.CallVoid ? 1 : 2;
×
339

340
        for (var i = call.Operands.Count - 1; i >= firstArg; i--)
×
341
        {
342
            switch (call.Operands[i])
×
343
            {
344
                case RuntimeMethodInfoAnalysisContext methodInfo:
345
                    return methodInfo;
×
346
                case LocalVariable { Type: RuntimeMethodInfoAnalysisContext methodInfoLocal }:
347
                    return methodInfoLocal;
×
348
            }
349
        }
350

351
        return null;
×
352
    }
353

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

377
        if (method != "")
×
378
        {
379
            instruction.Operands[0] = method;
×
380
        }
381
    }
×
382

383
    // Because of il2cpp fields (like cctor_finished_or_no_cctor) [local @ reg+offset] sometimes can't be resolved, but this works for now
384
    private static void ResolveGetter(MethodAnalysisContext method)
385
    {
386
        if (!method.Name.StartsWith("get_"))
×
387
            return;
×
388

389
        // Default get: Return [this @ reg+offset]
390
        var instructions = method.ControlFlowGraph!.Instructions;
×
391
        if (instructions.Count == 1)
×
392
        {
393
            var instr = instructions[0];
×
394

395
            if (instr.OpCode != OpCode.Return
×
396
                || instr.Operands.Count < 1
×
397
                || instr.Operands[0] is not MemoryOperand memory
×
398
                || memory.Index != null || memory.Scale != 0
×
399
                || memory.Base is not LocalVariable local)
×
400
                return;
×
401

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

404
            var field = method.DeclaringType!.Fields.Find(f => f.Name == fieldName);
×
405
            if (field == null)
×
406
                return;
×
407

408
            instr.Operands[0] = new FieldReference(field, local, (int)memory.Addend);
×
409
        }
410
    }
×
411
}
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