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

SamboyCoding / Cpp2IL / 30751767570

02 Aug 2026 02:17PM UTC coverage: 35.984% (-0.4%) from 36.382%
30751767570

push

github

SamboyCoding
Decompiler: Remove implicit null checks, resolve fields on generics, resolve generic methods which aren't in the metadata by address if we can

2857 of 9122 branches covered (31.32%)

Branch coverage included in aggregate %.

0 of 108 new or added lines in 4 files covered. (0.0%)

2 existing lines in 2 files now uncovered.

5293 of 13527 relevant lines covered (39.13%)

163430.95 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;
×
NEW
102
                var owner = staticOwner ?? local.Type;
×
NEW
103
                var genericOwner = owner as GenericInstanceTypeAnalysisContext;
×
104

105
                FieldAnalysisContext? field;
NEW
106
                if (genericOwner != null && staticOwner == null)
×
107
                {
108
                    // metadata has all-0 offsets for generic definitions, so recompute layout
109
                    // TODO support user-defined value types
NEW
110
                    if (genericOwner.GenericArguments.Any(a => a.IsValueType))
×
111
                        continue;
112

NEW
113
                    field = GenericInstanceFieldLayout.FindFieldAtOffset(genericOwner, memory.Addend);
×
114
                }
115
                else
116
                {
117
                    // a generic instance keeps its members on the definition, so look there
NEW
118
                    var candidates = (genericOwner?.GenericType ?? owner).Fields;
×
NEW
119
                    field = candidates.FirstOrDefault(f => f.IsStatic == (staticOwner != null) && f.BackingData?.FieldOffset == memory.Addend);
×
120
                }
121

122
                if (field == null) // TODO: Support nested fields (Field1.Field2.Field3)
×
123
                    continue;
124

125
                // make sure we have a full GIT for field access. open type is bad.
NEW
126
                if (genericOwner != null)
×
UNCOV
127
                    field = new ConcreteGenericFieldAnalysisContext(field, genericOwner);
×
128

129
                instruction.SetOperand(i, new FieldReference(field, local, (int)memory.Addend));
×
130
                changed = true;
×
131
            }
132
        }
133

134
        return changed;
×
135
    }
136

137
    private static void ResolveCalls(MethodAnalysisContext method)
138
    {
139
        foreach (var block in method.ControlFlowGraph!.Blocks)
×
140
        {
141
            if (block.BlockType != BlockType.Call && block.BlockType != BlockType.TailCall)
×
142
                continue;
143

144
            var callInstruction = block.Instructions[^1];
×
145
            if (callInstruction.Operands[0] is not Immediate dest)
×
146
                continue;
147

148
            var target = dest.UnsignedValue;
×
149

150
            var keyFunctionAddresses = method.AppContext.GetOrCreateKeyFunctionAddresses();
×
151

152
            if (keyFunctionAddresses.IsKeyFunctionAddress(target))
×
153
            {
154
                HandleKeyFunction(method.AppContext, callInstruction, target, keyFunctionAddresses);
×
155
                continue;
×
156
            }
157

158
            //Non-key function call. Try to find a single match
159
            if (!method.AppContext.MethodsByAddress.TryGetValue(target, out var targetMethods))
×
160
            {
161
                // Not a managed method at all. It may be one of the runtime helpers that exist purely to
162
                // throw, in which case restore the throw itself
163
                if (ThrowHelperRecovery.GetThrownException(method.AppContext, target) is { } thrown)
×
164
                {
165
                    callInstruction.OpCode = OpCode.Throw;
×
166
                    callInstruction.SetOperands(thrown);
×
167
                }
168

169
                continue;
×
170
            }
171

172
            // Duplicated/Shared method bodies are resolved later in ResolveCallsViaMethodInfo/ResolveAmbiguousCalls.
173
            if (targetMethods is not [{ } singleTargetMethod])
×
174
                continue;
175

176
            callInstruction.SetOperand(0, singleTargetMethod);
×
177
        }
178

179
        method.ControlFlowGraph.MergeCallBlocks();
×
180
    }
×
181

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

196
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
197
        {
198
            if (!instruction.IsCall)
×
199
                continue;
200

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

205
            if (!method.AppContext.MethodsByAddress.TryGetValue(target.UnsignedValue, out var candidates) || candidates.Count < 2)
×
206
                continue;
207

NEW
208
            if (GetReceiver(instruction) is not { Type: { } receiverType } receiver)
×
209
                continue;
210

211
            // Prefer picking base ctor if we are a ctor
NEW
212
            var callerIsCtor = method.Name == ".ctor" && receiver.IsThis;
×
213

214
            // Handle methods with shared bodies
NEW
215
            var match = default(MethodAnalysisContext);
×
216

NEW
217
            for (var type = receiverType; type != null && match == null; type = type.BaseType)
×
218
            {
NEW
219
                var matches = candidates.Where(c => !c.IsStatic && ReferenceEquals(c.DeclaringType, type)).ToList();
×
220

NEW
221
                if (matches.Count > 1 && callerIsCtor)
×
NEW
222
                    matches = matches.Where(c => c.Name == ".ctor").ToList();
×
223

NEW
224
                if (matches.Count > 1)
×
225
                    break;
226

NEW
227
                match = matches.SingleOrDefault();
×
228
            }
229

NEW
230
            if (match == null)
×
231
                continue;
232

233
            instruction.SetOperand(0, match);
×
234
            changed = true;
×
235
        }
236

237
        return changed;
×
238
    }
239

240
    // The receiver ('this') of a call is the first integer-slot argument: operand 1 for CallVoid
241
    // (after the target), operand 2 for Call (after the target and the return value).
242
    private static LocalVariable? GetReceiver(Instruction call)
243
    {
244
        var index = call.OpCode == OpCode.CallVoid ? 1 : 2;
×
245
        return index < call.Operands.Count ? call.Operands[index] as LocalVariable : null;
×
246
    }
247

248
    /// <summary>
249
    /// Resolves any Call (theoretically should always be a CallVoid) target directly after a Newobj to a constructor call.
250
    /// </summary>
251
    public static bool ResolveConstructorCalls(MethodAnalysisContext method)
252
    {
253
        var definitions = new Dictionary<LocalVariable, Instruction>();
×
254
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
255
            if (instruction.Destination is LocalVariable definition)
×
256
                definitions[definition] = instruction;
×
257

258
        var changed = false;
×
259

260
        foreach (var instruction in method.ControlFlowGraph.Instructions)
×
261
        {
262
            if (!instruction.IsCall || instruction.Operands[0] is not Immediate callTarget)
×
263
                continue;
264

265
            if (!method.AppContext.MethodsByAddress.TryGetValue(callTarget.UnsignedValue, out var candidates))
×
266
                continue;
267

268
            if (GetReceiver(instruction) is not { } receiver || AllocatedType(receiver, definitions) is not { } allocatedType)
×
269
                continue;
270

271
            var constructor = candidates.FirstOrDefault(c => !c.IsStatic && c.Name == ".ctor" && ReferenceEquals(c.DeclaringType, allocatedType));
×
272
            if (constructor == null)
×
273
                continue;
274

275
            instruction.SetOperand(0, constructor);
×
276
            changed = true;
×
277
        }
278

279
        return changed;
×
280
    }
281

282
    // Follow SSA copies from a local back to the Newobj that produced the value
283
    private static TypeAnalysisContext? AllocatedType(LocalVariable local, Dictionary<LocalVariable, Instruction> definitions)
284
    {
285
        var visited = new HashSet<LocalVariable>();
×
286

287
        while (visited.Add(local) && definitions.TryGetValue(local, out var definition))
×
288
        {
289
            switch (definition.OpCode)
×
290
            {
291
                case OpCode.Newobj:
292
                    return (definition.Operands[0] as LocalVariable)?.Type;
×
293
                case OpCode.Move when definition.Operands[1] is LocalVariable source:
×
294
                    local = source;
×
295
                    continue;
×
296
            }
297

298
            break;
299
        }
300

301
        return null;
×
302
    }
303

304
    /// <summary>
305
    /// Resolves calls whose address maps to more than one method by reading the runtime
306
    /// <c>MethodInfo*</c> the caller passes in, if there is one.
307
    /// </summary>
308
    public static bool ResolveCallsViaMethodInfo(MethodAnalysisContext method)
309
    {
310
        var changed = false;
×
311

312
        foreach (var instruction in method.ControlFlowGraph!.Instructions)
×
313
        {
314
            if (!instruction.IsCall)
×
315
                continue;
316

317
            if (instruction.Operands[0] is not Immediate target)
×
318
                //Already resolved
319
                continue;
320

321
            if (GetMethodInfoArgument(instruction) is not { RepresentedMethod: { } representedMethod })
×
322
                //No MethodInfo to work with
323
                continue;
324

NEW
325
            if (!method.AppContext.MethodsByAddress.TryGetValue(target.UnsignedValue, out var candidates))
×
326
            {
327
                // Some shared generic bodies aren't in the address map at all (todo investigate?).
328
                // Il2cpp still passes the concrete MethodInfo as the hidden final parameter, so we can use a methodof there if we have one.
NEW
329
                var firstArg = instruction.OpCode == OpCode.CallVoid ? 1 : 2;
×
NEW
330
                var hiddenParamIndex = firstArg + (representedMethod.IsStatic ? 0 : 1) + representedMethod.Parameters.Count;
×
331

NEW
332
                if (hiddenParamIndex >= instruction.Operands.Count
×
NEW
333
                    || AsMethodInfo(instruction.Operands[hiddenParamIndex]) == null)
×
334
                    continue;
335

NEW
336
                instruction.SetOperand(0, representedMethod);
×
NEW
337
                changed = true;
×
NEW
338
                continue;
×
339
            }
340

NEW
341
            if (candidates.Count < 2)
×
342
                continue;
343

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

349
            instruction.SetOperand(0, representedMethod);
×
350
            changed = true;
×
351
        }
352

353
        return changed;
×
354
    }
355

356
    private static MethodAnalysisContext BaseMethodOf(MethodAnalysisContext method) =>
357
        method is ConcreteGenericMethodAnalysisContext { BaseMethodContext: { } baseMethod } ? baseMethod : method;
×
358

359
    private static RuntimeMethodInfoAnalysisContext? GetMethodInfoArgument(Instruction call)
360
    {
361
        var firstArg = call.OpCode == OpCode.CallVoid ? 1 : 2;
×
362

363
        for (var i = call.Operands.Count - 1; i >= firstArg; i--)
×
364
        {
NEW
365
            if (AsMethodInfo(call.Operands[i]) is { } methodInfo)
×
NEW
366
                return methodInfo;
×
367
        }
368

369
        return null;
×
370
    }
371

372
    private static RuntimeMethodInfoAnalysisContext? AsMethodInfo(IOperand operand) =>
NEW
373
        operand switch
×
NEW
374
        {
×
NEW
375
            RuntimeMethodInfoAnalysisContext methodInfo => methodInfo,
×
NEW
376
            LocalVariable { Type: RuntimeMethodInfoAnalysisContext methodInfoLocal } => methodInfoLocal,
×
NEW
377
            _ => null
×
NEW
378
        };
×
379

380
    private static void HandleKeyFunction(ApplicationAnalysisContext appContext, Instruction instruction, ulong target, BaseKeyFunctionAddresses kFA)
381
    {
382
        var method = "";
×
383
        if (target == kFA.il2cpp_codegen_initialize_method || target == kFA.il2cpp_codegen_initialize_runtime_metadata)
×
384
        {
385
            if (appContext.MetadataVersion < 27)
×
386
            {
387
                method = nameof(kFA.il2cpp_codegen_initialize_method);
×
388
            }
389
            else
390
            {
391
                method = nameof(kFA.il2cpp_codegen_initialize_runtime_metadata);
×
392
            }
393
        }
394
        else
395
        {
396
            var pairs = kFA.Pairs.ToList();
×
397
            var key = pairs.FirstOrDefault(pair => pair.Value == target).Key;
×
398
            if (key == null)
×
399
                return;
×
400
            method = key;
×
401
        }
402

403
        if (method != "")
×
404
        {
405
            instruction.SetOperand(0, new StringLiteral(method));
×
406
        }
407
    }
×
408

409
    // Because of il2cpp fields (like cctor_finished_or_no_cctor) [local @ reg+offset] sometimes can't be resolved, but this works for now
410
    private static void ResolveGetter(MethodAnalysisContext method)
411
    {
412
        if (!method.Name.StartsWith("get_"))
×
413
            return;
×
414

415
        // Default get: Return [this @ reg+offset]
416
        var instructions = method.ControlFlowGraph!.Instructions;
×
417
        if (instructions.Count == 1)
×
418
        {
419
            var instr = instructions[0];
×
420

421
            if (instr.OpCode != OpCode.Return
×
422
                || instr.Operands.Count < 1
×
423
                || instr.Operands[0] is not MemoryOperand memory
×
424
                || memory.Index != null || memory.Scale != 0
×
425
                || memory.Base is not LocalVariable local)
×
426
                return;
×
427

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

430
            var field = method.DeclaringType!.Fields.Find(f => f.Name == fieldName);
×
431
            if (field == null)
×
432
                return;
×
433

434
            instr.SetOperand(0, new FieldReference(field, local, (int)memory.Addend));
×
435
        }
436
    }
×
437
}
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