-
-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathMethodAnalysisContext.cs
More file actions
412 lines (337 loc) · 14.5 KB
/
MethodAnalysisContext.cs
File metadata and controls
412 lines (337 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Cpp2IL.Core.Graphs;
using Cpp2IL.Core.Graphs.Processors;
using Cpp2IL.Core.ISIL;
using Cpp2IL.Core.Logging;
using Cpp2IL.Core.Utils;
using LibCpp2IL;
using LibCpp2IL.Metadata;
using StableNameDotNet.Providers;
namespace Cpp2IL.Core.Model.Contexts;
/// <summary>
/// Represents one method within the application. Can be analyzed to attempt to reconstruct the function body.
/// </summary>
public class MethodAnalysisContext : HasGenericParameters, IMethodInfoProvider
{
/// <summary>
/// The underlying metadata for the method.
///
/// Nullable iff this is a subclass.
/// </summary>
public readonly Il2CppMethodDefinition? Definition;
/// <summary>
/// The analysis context for the declaring type of this method.
/// </summary>
public readonly TypeAnalysisContext? DeclaringType;
/// <summary>
/// The address of this method as defined in the underlying metadata.
/// </summary>
public virtual ulong UnderlyingPointer => Definition?.MethodPointer ?? throw new("Subclasses of MethodAnalysisContext should override UnderlyingPointer");
public ulong Rva => UnderlyingPointer == 0 || LibCpp2IlMain.Binary == null ? 0 : LibCpp2IlMain.Binary.GetRva(UnderlyingPointer);
/// <summary>
/// The raw method body as machine code in the active instruction set.
/// </summary>
public ReadOnlyMemory<byte> RawBytes => rawMethodBody ??= InitRawBytes();
/// <summary>
/// The first-stage-analyzed Instruction-Set-Independent Language Instructions.
/// </summary>
public List<InstructionSetIndependentInstruction>? ConvertedIsil;
/// <summary>
/// The control flow graph for this method, if one is built.
/// </summary>
public ISILControlFlowGraph? ControlFlowGraph;
public List<ParameterAnalysisContext> Parameters = [];
/// <summary>
/// Does this method return void?
/// </summary>
public bool IsVoid => ReturnType == AppContext.SystemTypes.SystemVoidType;
public bool IsStatic => (Attributes & MethodAttributes.Static) != 0;
public bool IsVirtual => (Attributes & MethodAttributes.Virtual) != 0;
public bool IsAbstract => (Attributes & MethodAttributes.Abstract) != 0;
public bool IsNewSlot => (Attributes & MethodAttributes.NewSlot) != 0;
protected override int CustomAttributeIndex => Definition?.customAttributeIndex ?? throw new("Subclasses of MethodAnalysisContext should override CustomAttributeIndex if they have custom attributes");
public override AssemblyAnalysisContext CustomAttributeAssembly => DeclaringType?.DeclaringAssembly ?? throw new("Subclasses of MethodAnalysisContext should override CustomAttributeAssembly if they have custom attributes");
public override string DefaultName => Definition?.Name ?? throw new("Subclasses of MethodAnalysisContext should override DefaultName");
public string FullName => DeclaringType == null ? Name : $"{DeclaringType.FullName}::{Name}";
public string FullNameWithSignature => $"{ReturnType.FullName} {FullName}({string.Join(", ", Parameters.Select(p => p.HumanReadableSignature))})";
public virtual MethodAttributes DefaultAttributes => Definition?.Attributes ?? throw new($"Subclasses of MethodAnalysisContext should override {nameof(DefaultAttributes)}");
public virtual MethodAttributes? OverrideAttributes { get; set; }
public MethodAttributes Attributes
{
get => OverrideAttributes ?? DefaultAttributes;
set => OverrideAttributes = value;
}
public virtual MethodImplAttributes DefaultImplAttributes => Definition?.MethodImplAttributes ?? throw new($"Subclasses of MethodAnalysisContext should override {nameof(DefaultImplAttributes)}");
public virtual MethodImplAttributes? OverrideImplAttributes { get; set; }
public MethodImplAttributes ImplAttributes
{
get => OverrideImplAttributes ?? DefaultImplAttributes;
set => OverrideImplAttributes = value;
}
public MethodAttributes Visibility
{
get
{
return Attributes & MethodAttributes.MemberAccessMask;
}
set
{
Attributes = (Attributes & ~MethodAttributes.MemberAccessMask) | (value & MethodAttributes.MemberAccessMask);
}
}
private List<GenericParameterTypeAnalysisContext>? _genericParameters;
public override List<GenericParameterTypeAnalysisContext> GenericParameters
{
get
{
// Lazy load the generic parameters
_genericParameters ??= Definition?.GenericContainer?.GenericParameters.Select(p => new GenericParameterTypeAnalysisContext(p, this)).ToList() ?? [];
return _genericParameters;
}
}
private ushort Slot => Definition?.slot ?? ushort.MaxValue;
public virtual TypeAnalysisContext DefaultReturnType => DeclaringType?.DeclaringAssembly.ResolveIl2CppType(Definition?.RawReturnType) ?? throw new($"Subclasses of MethodAnalysisContext should override {nameof(DefaultReturnType)}");
public TypeAnalysisContext? OverrideReturnType { get; set; }
//TODO Support custom attributes on return types (v31 feature)
public TypeAnalysisContext ReturnType
{
get => OverrideReturnType ?? DefaultReturnType;
set => OverrideReturnType = value;
}
protected ReadOnlyMemory<byte>? rawMethodBody;
public MethodAnalysisContext? BaseMethod
{
get
{
if (Definition == null)
return null;
var vtable = DeclaringType?.Definition?.VTable;
if (vtable == null)
return null;
for (var i = 0; i < vtable.Length; ++i)
{
var vtableEntry = vtable[i];
if (vtableEntry is null or { Type: not MetadataUsageType.MethodDef } || vtableEntry.AsMethod() != Definition)
continue;
var baseType = DeclaringType?.DefaultBaseType;
while (baseType is not null)
{
if (TryGetMethodForSlot(baseType, i, out var method))
{
return method;
}
baseType = baseType.DefaultBaseType;
}
}
return null;
}
}
private List<MethodAnalysisContext>? _overrides;
/// <summary>
/// The set of interface methods which this method explicitly overrides.
/// </summary>
public List<MethodAnalysisContext> Overrides
{
get
{
// Lazy load the overrides
return _overrides ??= GetOverrides().ToList();
}
}
private IEnumerable<MethodAnalysisContext> GetOverrides()
{
if (Definition == null)
return [];
var declaringTypeDefinition = DeclaringType?.Definition;
if (declaringTypeDefinition == null)
return [];
var vtable = declaringTypeDefinition.VTable;
if (vtable == null)
return [];
return GetOverriddenMethods(declaringTypeDefinition, vtable);
IEnumerable<MethodAnalysisContext> GetOverriddenMethods(Il2CppTypeDefinition declaringTypeDefinition, MetadataUsage?[] vtable)
{
for (var i = 0; i < vtable.Length; ++i)
{
var vtableEntry = vtable[i];
if (vtableEntry is null or { Type: not MetadataUsageType.MethodDef })
continue;
if (vtableEntry.AsMethod() != Definition)
continue;
// Interface inheritance
foreach (var interfaceOffset in declaringTypeDefinition.InterfaceOffsets)
{
if (i >= interfaceOffset.offset)
{
var interfaceTypeContext = interfaceOffset.Type.ToContext(CustomAttributeAssembly);
if (interfaceTypeContext != null && TryGetMethodForSlot(interfaceTypeContext, i - interfaceOffset.offset, out var method))
{
yield return method;
}
}
}
}
}
}
private static bool TryGetMethodForSlot(TypeAnalysisContext declaringType, int slot, [NotNullWhen(true)] out MethodAnalysisContext? method)
{
if (declaringType is GenericInstanceTypeAnalysisContext genericInstanceType)
{
var genericMethod = genericInstanceType.GenericType.Methods.FirstOrDefault(m => m.Slot == slot);
if (genericMethod is not null)
{
method = new ConcreteGenericMethodAnalysisContext(genericMethod, genericInstanceType.GenericArguments, []);
return true;
}
}
else
{
var baseMethod = declaringType.Methods.FirstOrDefault(m => m.Slot == slot);
if (baseMethod is not null)
{
method = baseMethod;
return true;
}
}
method = null;
return false;
}
private static readonly List<IBlockProcessor> blockProcessors =
[
new MetadataProcessor(),
new CallProcessor()
];
public MethodAnalysisContext(Il2CppMethodDefinition? definition, TypeAnalysisContext parent) : base(definition?.token ?? 0, parent.AppContext)
{
DeclaringType = parent;
Definition = definition;
if (Definition != null)
{
InitCustomAttributeData();
for (var i = 0; i < Definition.InternalParameterData!.Length; i++)
{
var parameterDefinition = Definition.InternalParameterData![i];
Parameters.Add(new(parameterDefinition, i, this));
}
}
else
rawMethodBody = Array.Empty<byte>();
}
[MemberNotNull(nameof(rawMethodBody))]
public void EnsureRawBytes()
{
rawMethodBody ??= InitRawBytes();
}
private ReadOnlyMemory<byte> InitRawBytes()
{
//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.
//E.g. UnityEngine.Purchasing.AppleCore.dll: UnityEngine.Purchasing.INativeAppleStore::SetUnityPurchasingCallback on among us (itch.io build)
if (Definition != null && Definition.MethodPointer != 0 && !Definition.Attributes.HasFlag(MethodAttributes.Abstract))
{
var ret = AppContext.InstructionSet.GetRawBytesForMethod(this, false);
if (ret.Length == 0)
{
Logger.VerboseNewline("\t\t\tUnexpectedly got 0-byte method body for " + this + $". Pointer was 0x{Definition.MethodPointer:X}", "MAC");
}
return ret;
}
else
return ReadOnlyMemory<byte>.Empty;
}
protected MethodAnalysisContext(ApplicationAnalysisContext context) : base(0, context)
{
rawMethodBody = ReadOnlyMemory<byte>.Empty;
}
[MemberNotNull(nameof(ConvertedIsil))]
public void Analyze()
{
if (ConvertedIsil != null)
return;
if (UnderlyingPointer == 0)
{
ConvertedIsil = [];
return;
}
ConvertedIsil = AppContext.InstructionSet.GetIsilFromMethod(this);
if (ConvertedIsil.Count == 0)
return; //Nothing to do, empty function
ControlFlowGraph = new ISILControlFlowGraph();
ControlFlowGraph.Build(ConvertedIsil);
// Post step to convert metadata usage. Ldstr Opcodes etc.
foreach (var block in ControlFlowGraph.Blocks)
{
foreach (var converter in blockProcessors)
{
converter.Process(this, block);
}
}
}
public void ReleaseAnalysisData()
{
ConvertedIsil = null;
ControlFlowGraph = null;
}
public ConcreteGenericMethodAnalysisContext MakeGenericInstanceMethod(params IEnumerable<TypeAnalysisContext> methodGenericParameters)
{
if (this is ConcreteGenericMethodAnalysisContext methodOnGenericInstanceType)
{
return new ConcreteGenericMethodAnalysisContext(methodOnGenericInstanceType.BaseMethodContext, methodOnGenericInstanceType.TypeGenericParameters, methodGenericParameters);
}
else
{
return new ConcreteGenericMethodAnalysisContext(this, [], methodGenericParameters);
}
}
public ConcreteGenericMethodAnalysisContext MakeConcreteGenericMethod(IEnumerable<TypeAnalysisContext> typeGenericParameters, IEnumerable<TypeAnalysisContext> methodGenericParameters)
{
if (this is ConcreteGenericMethodAnalysisContext)
{
throw new InvalidOperationException($"Attempted to make a {nameof(ConcreteGenericMethodAnalysisContext)} concrete: {this}");
}
else
{
return new ConcreteGenericMethodAnalysisContext(this, typeGenericParameters, methodGenericParameters);
}
}
public override string ToString() => $"Method: {FullName}";
#region StableNameDot implementation
ITypeInfoProvider IMethodInfoProvider.ReturnType =>
Definition!.RawReturnType!.ThisOrElementIsGenericParam()
? new GenericParameterTypeInfoProviderWrapper(Definition.RawReturnType!.GetGenericParamName())
: TypeAnalysisContext.GetSndnProviderForType(AppContext, Definition!.RawReturnType);
IEnumerable<IParameterInfoProvider> IMethodInfoProvider.ParameterInfoProviders => Parameters;
string IMethodInfoProvider.MethodName => Name;
MethodAttributes IMethodInfoProvider.MethodAttributes => Attributes;
MethodSemantics IMethodInfoProvider.MethodSemantics
{
get
{
if (DeclaringType != null)
{
//This one is a bit trickier, as il2cpp doesn't use semantics.
foreach (var prop in DeclaringType.Properties)
{
if (prop.Getter == this)
return MethodSemantics.Getter;
if (prop.Setter == this)
return MethodSemantics.Setter;
}
foreach (var evt in DeclaringType.Events)
{
if (evt.Adder == this)
return MethodSemantics.AddOn;
if (evt.Remover == this)
return MethodSemantics.RemoveOn;
if (evt.Invoker == this)
return MethodSemantics.Fire;
}
}
return 0;
}
}
#endregion
}