Skip to content

Commit ea00fc3

Browse files
committed
Factor out some usage of static state
1 parent e45fc35 commit ea00fc3

File tree

14 files changed

+87
-87
lines changed

14 files changed

+87
-87
lines changed

Cpp2IL.Core/Cpp2IlApi.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ private static void OnLibInitialized()
107107

108108
var start = DateTime.Now;
109109
Logger.InfoNewline("Creating application model...");
110-
CurrentAppContext = new(LibCpp2IlMain.Binary, LibCpp2IlMain.TheMetadata!, LibCpp2IlMain.MetadataVersion);
110+
CurrentAppContext = new(LibCpp2IlMain.Binary, LibCpp2IlMain.TheMetadata!);
111111
Logger.InfoNewline($"Application model created in {(DateTime.Now - start).TotalMilliseconds}ms");
112112
}
113113

Cpp2IL.Core/Model/Contexts/ApplicationAnalysisContext.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public class ApplicationAnalysisContext : ContextWithDataStorage
2828
/// <summary>
2929
/// The version of the IL2CPP metadata file this application was loaded from.
3030
/// </summary>
31-
public readonly float MetadataVersion;
31+
public float MetadataVersion => Metadata.MetadataVersion;
3232

3333
/// <summary>
3434
/// The instruction set helper class associated with the instruction set that this application was compiled with.
@@ -70,11 +70,10 @@ public class ApplicationAnalysisContext : ContextWithDataStorage
7070
/// </summary>
7171
public bool HasFinishedInitializing { get; private set; }
7272

73-
public ApplicationAnalysisContext(Il2CppBinary binary, Il2CppMetadata metadata, float metadataVersion)
73+
public ApplicationAnalysisContext(Il2CppBinary binary, Il2CppMetadata metadata)
7474
{
7575
Binary = binary;
7676
Metadata = metadata;
77-
MetadataVersion = metadataVersion;
7877

7978
try
8079
{

Cpp2IL.Core/Model/Contexts/HasCustomAttributes.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,8 @@ protected void InitCustomAttributeData()
9898
}
9999

100100
AttributeTypes = Enumerable.Range(AttributeTypeRange.start, AttributeTypeRange.count)
101-
.Select(attrIdx => LibCpp2IlMain.TheMetadata!.attributeTypes[attrIdx])
102-
.Select(typeIdx => LibCpp2IlMain.Binary!.GetType(typeIdx))
101+
.Select(attrIdx => AppContext.Metadata!.attributeTypes![attrIdx]) //Not null because we've checked we're not on v29
102+
.Select(typeIdx => AppContext.Binary!.GetType(typeIdx))
103103
.ToList();
104104

105105
ulong generatorPtr;

Cpp2IL.Core/ProcessingLayers/AttributeInjectorProcessingLayer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ private static void InjectTokenAttribute(ApplicationAnalysisContext appContext)
133133

134134
private static void InjectAttributeAttribute(ApplicationAnalysisContext appContext)
135135
{
136-
if (LibCpp2IlMain.MetadataVersion >= 29f)
136+
if (appContext.MetadataVersion >= 29f)
137137
{
138138
//All attributes should be fully serializable anyway, as they're stored in metadata
139139
//However, we still need to read them all

Cpp2IL.Core/Utils/AsmResolver/AsmResolverUtils.cs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ public static TypeSignature GetTypeSignatureFromIl2CppType(ModuleDefinition modu
112112

113113
//Get base type
114114
TypeDefsByIndex.TryGetValue(genericClass.TypeDefinitionIndex, out var typeDefinition);
115-
if (LibCpp2IlMain.MetadataVersion >= 27f)
115+
if (Cpp2IlApi.CurrentAppContext!.MetadataVersion >= 27f) //TODO: we should pass in the app context to this method
116116
{
117117
//V27 - type indexes are pointers now.
118118
var type = LibCpp2IlMain.Binary!.ReadReadableAtVirtualAddress<Il2CppType>((ulong)genericClass.TypeDefinitionIndex);
@@ -121,15 +121,6 @@ public static TypeSignature GetTypeSignatureFromIl2CppType(ModuleDefinition modu
121121

122122
var genericInstanceType = new GenericInstanceTypeSignature(typeDefinition!, typeDefinition!.IsValueType);
123123

124-
//If the generic type is declared in a type with generic params, we have to fill all its parent's params with dummy values.
125-
// if (typeDefinition.DeclaringType?.GenericParameters?.Count is {} declTypeGpCount)
126-
// {
127-
// for (var i = 0; i < declTypeGpCount; i++)
128-
// {
129-
// genericInstanceType.TypeArguments.Add(TypeDefinitionsAsmResolver.Object.ToTypeSignature());
130-
// }
131-
// }
132-
133124
//Get generic arguments
134125
var genericArgumentTypes = genericClass.Context.ClassInst.Types;
135126

Cpp2IL.Core/Utils/MiscUtils.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,8 @@ internal static byte[] RawBytes(IConvertible original) =>
170170

171171
private static void InitFunctionStarts()
172172
{
173-
_allKnownFunctionStarts = LibCpp2IlMain.TheMetadata!.methodDefs.Select(m => m.MethodPointer)
174-
.Concat(LibCpp2IlMain.Binary!.ConcreteGenericImplementationsByAddress.Keys)
173+
_allKnownFunctionStarts = Cpp2IlApi.CurrentAppContext!.Metadata.methodDefs.Select(m => m.MethodPointer)
174+
.Concat(Cpp2IlApi.CurrentAppContext.Binary.ConcreteGenericImplementationsByAddress.Keys)
175175
.Concat(SharedState.AttributeGeneratorStarts)
176176
.ToList();
177177

@@ -264,10 +264,10 @@ public static string AnalyzeStackTracePointers(ulong[] pointers)
264264
{
265265
// var pointers = new ulong[] {0x52e6ba0, 0x52ad3a0, 0x11b09714, 0x40a990c, 0xd172c68, 0xa2c0514, 0x35ea45c, 0x1fc43208};
266266

267-
var methodsSortedByPointer = LibCpp2IlMain.TheMetadata!.methodDefs.ToList();
267+
var methodsSortedByPointer = Cpp2IlApi.CurrentAppContext!.Metadata.methodDefs.ToList();
268268
methodsSortedByPointer.SortByExtractedKey(m => m.MethodPointer);
269269

270-
var genericMethodsSortedByPointer = LibCpp2IlMain.Binary!.ConcreteGenericImplementationsByAddress.ToList();
270+
var genericMethodsSortedByPointer = Cpp2IlApi.CurrentAppContext.Binary.ConcreteGenericImplementationsByAddress.ToList();
271271
genericMethodsSortedByPointer.SortByExtractedKey(m => m.Key);
272272

273273
var stack = pointers.Select(p =>

Cpp2IL.Plugin.StrippedCodeRegSupport/StrippedCodeRegSupportPlugin.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ private void OnReadFail(Il2CppBinary binary, Il2CppMetadata metadata, ref Il2Cpp
3030
//We don't have a CodeRegistration, so we need to try and find one.
3131
Logger.InfoNewline("Received read failure for CodeRegistration, implying it may have been stripped. Attempting to work around...");
3232

33-
if (LibCpp2IlMain.MetadataVersion < MinSupportedMetadataVersion)
33+
if (metadata.MetadataVersion < MinSupportedMetadataVersion)
3434
{
3535
Logger.ErrorNewline($"This game's metadata version is too old to support this plugin (it needs to be at least Metadata {MinSupportedMetadataVersion:F1}, i.e. Unity 2020.2 or newer).");
3636
return;

LibCpp2IL/BinarySearcher.cs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Text;
77
using LibCpp2IL.BinaryStructures;
88
using LibCpp2IL.Logging;
9+
using LibCpp2IL.Metadata;
910
using LibCpp2IL.NintendoSwitch;
1011
using LibCpp2IL.Wasm;
1112

@@ -124,7 +125,7 @@ public ulong FindCodeRegistrationPre2019()
124125
}
125126

126127
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
127-
internal ulong FindCodeRegistrationPost2019()
128+
internal ulong FindCodeRegistrationPost2019(Il2CppMetadata metadata)
128129
{
129130
//Works only on >=24.2
130131
var mscorlibs = FindAllStrings("mscorlib.dll\0").Select(idx => binary.MapRawAddressToVirtual(idx)).ToList();
@@ -148,7 +149,7 @@ internal ulong FindCodeRegistrationPost2019()
148149
var ptrSize = (binary.is32Bit ? 4u : 8u);
149150

150151
List<ulong>? pCodegenModules = null;
151-
if (LibCpp2IlMain.MetadataVersion < 27f)
152+
if (metadata.MetadataVersion < 27f)
152153
{
153154
//Pre-v27, mscorlib is the first codegen module, so *MscorlibCodegenEntryInCodegenModulesList == g_CodegenModules, so we can just find a pointer to this.
154155
if (pMscorlibCodegenEntryInCodegenModulesList.Count == 1)
@@ -209,7 +210,7 @@ internal ulong FindCodeRegistrationPost2019()
209210

210211
//We have pCodegenModules which *should* be x-reffed in the last pointer of Il2CppCodeRegistration.
211212
//So, subtract the size of one pointer from that...
212-
var bytesToGoBack = (ulong)Il2CppCodeRegistration.GetStructSize(binary.is32Bit, LibCpp2IlMain.MetadataVersion) - ptrSize;
213+
var bytesToGoBack = (ulong)Il2CppCodeRegistration.GetStructSize(binary.is32Bit, metadata.MetadataVersion) - ptrSize;
213214

214215
LibLogger.VerboseNewline($"\t\t\tpCodegenModules is the second-to-last field of the codereg struct. Therefore on this version and architecture, we need to subtract {bytesToGoBack} bytes from its address to get pCodeReg");
215216

@@ -308,7 +309,7 @@ public ulong FindMetadataRegistrationPre24_5()
308309
return 0;
309310
}
310311

311-
public ulong FindMetadataRegistrationPost24_5()
312+
public ulong FindMetadataRegistrationPost24_5(Il2CppMetadata metadata)
312313
{
313314
var ptrSize = binary.is32Bit ? 4ul : 8ul;
314315
var sizeOfMr = (uint)Il2CppMetadataRegistration.GetStructSize(binary.is32Bit);
@@ -364,29 +365,29 @@ public ulong FindMetadataRegistrationPost24_5()
364365
if (ok)
365366
{
366367
var metaReg = binary.ReadReadableAtVirtualAddress<Il2CppMetadataRegistration>(va);
367-
if (LibCpp2IlMain.MetadataVersion >= 27f && (metaReg.metadataUsagesCount != 0 || metaReg.metadataUsages != 0))
368+
if (metadata.MetadataVersion >= 27f && (metaReg.metadataUsagesCount != 0 || metaReg.metadataUsages != 0))
368369
{
369370
//Too many metadata usages - should be 0 on v27
370371
LibLogger.VerboseNewline($"\t\t\tWarning: metadata registration 0x{va:X} has {metaReg.metadataUsagesCount} metadata usages at a pointer of 0x{metaReg.metadataUsages:X}. We're on v27, these should be 0.");
371372
// continue;
372373
}
373374

374-
if (metaReg.typeDefinitionsSizesCount != LibCpp2IlMain.TheMetadata!.typeDefs.Length)
375+
if (metaReg.typeDefinitionsSizesCount != metadata.typeDefs.Length)
375376
{
376-
LibLogger.VerboseNewline($"\t\t\tRejecting metadata registration 0x{va:X} because it has {metaReg.typeDefinitionsSizesCount} type def sizes, while metadata file defines {LibCpp2IlMain.TheMetadata!.typeDefs.Length} type defs");
377+
LibLogger.VerboseNewline($"\t\t\tRejecting metadata registration 0x{va:X} because it has {metaReg.typeDefinitionsSizesCount} type def sizes, while metadata file defines {metadata.typeDefs.Length} type defs");
377378
continue;
378379
}
379380

380-
if (metaReg.numTypes < LibCpp2IlMain.TheMetadata!.typeDefs.Length)
381+
if (metaReg.numTypes < metadata.typeDefs.Length)
381382
{
382-
LibLogger.VerboseNewline($"\t\t\tRejecting metadata registration 0x{va:X} because it has {metaReg.numTypes} types, which is less than metadata-file-defined type def count of {LibCpp2IlMain.TheMetadata!.typeDefs.Length}");
383+
LibLogger.VerboseNewline($"\t\t\tRejecting metadata registration 0x{va:X} because it has {metaReg.numTypes} types, which is less than metadata-file-defined type def count of {metadata.typeDefs.Length}");
383384
continue;
384385
}
385386

386-
if (metaReg.fieldOffsetsCount != LibCpp2IlMain.TheMetadata!.typeDefs.Length)
387+
if (metaReg.fieldOffsetsCount != metadata.typeDefs.Length)
387388
{
388389
//If we see any cases of failing to find meta reg and this line is in verbose log, maybe the assumption (num field offsets == num type defs) is wrong.
389-
LibLogger.VerboseNewline($"\t\t\tRejecting metadata registration 0x{va:X} because it has {metaReg.fieldOffsetsCount} field offsets, while metadata file defines {LibCpp2IlMain.TheMetadata!.typeDefs.Length} type defs");
390+
LibLogger.VerboseNewline($"\t\t\tRejecting metadata registration 0x{va:X} because it has {metaReg.fieldOffsetsCount} field offsets, while metadata file defines {metadata.typeDefs.Length} type defs");
390391
continue;
391392
}
392393

LibCpp2IL/Elf/ElfFile.cs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.IO;
55
using System.Linq;
66
using LibCpp2IL.Logging;
7+
using LibCpp2IL.Metadata;
78
using LibCpp2IL.PE;
89

910
namespace LibCpp2IL.Elf;
@@ -470,7 +471,7 @@ private void ProcessInitializers()
470471
_initializerPointers = initArray.Select(a => MapVirtualAddressToRaw(a)).ToList();
471472
}
472473

473-
public override (ulong pCodeRegistration, ulong pMetadataRegistration) FindCodeAndMetadataReg(int methodCount, int typeDefinitionsCount)
474+
public override (ulong pCodeRegistration, ulong pMetadataRegistration) FindCodeAndMetadataReg(Il2CppMetadata metadata)
474475
{
475476
//Let's just try and be cheap here and find them in the symbol table.
476477

@@ -492,21 +493,21 @@ public override (ulong pCodeRegistration, ulong pMetadataRegistration) FindCodeA
492493
LibLogger.VerboseNewline("Didn't find them, scanning binary...");
493494

494495
//Well, that didn't work. Look for the specific initializer function which calls into Il2CppCodegenRegistration.
495-
if (InstructionSetId == DefaultInstructionSets.ARM_V7 && LibCpp2IlMain.MetadataVersion < 24.2f)
496+
if (InstructionSetId == DefaultInstructionSets.ARM_V7 && metadata.MetadataVersion < 24.2f)
496497
{
497498
var ret = FindCodeAndMetadataRegArm32();
498499
if (ret != (0, 0))
499500
return ret;
500501
}
501502

502-
if (InstructionSetId == DefaultInstructionSets.ARM_V8 && LibCpp2IlMain.MetadataVersion < 24.2f)
503+
if (InstructionSetId == DefaultInstructionSets.ARM_V8 && metadata.MetadataVersion < 24.2f)
503504
{
504505
var ret = FindCodeAndMetadataRegArm64();
505506
if (ret != (0, 0))
506507
return ret;
507508
}
508509

509-
return FindCodeAndMetadataRegDefaultBehavior(methodCount, typeDefinitionsCount);
510+
return FindCodeAndMetadataRegDefaultBehavior(metadata);
510511
}
511512

512513
private (ulong codeReg, ulong metaReg) FindCodeAndMetadataRegArm32()
@@ -662,17 +663,20 @@ public override (ulong pCodeRegistration, ulong pMetadataRegistration) FindCodeA
662663
return (0, 0);
663664
}
664665

665-
private (ulong codeReg, ulong metaReg) FindCodeAndMetadataRegDefaultBehavior(int methodCount, int typeDefinitionsCount)
666+
private (ulong codeReg, ulong metaReg) FindCodeAndMetadataRegDefaultBehavior(Il2CppMetadata metadata)
666667
{
668+
var methodCount = metadata.methodDefs.Count(x => x.methodIndex >= 0);
669+
var typeDefinitionsCount = metadata.typeDefs.Length;
670+
667671
LibLogger.VerboseNewline("Searching for il2cpp structures in an ELF binary using non-arch-specific method...");
668672
var searcher = new BinarySearcher(this, methodCount, typeDefinitionsCount);
669673

670674
LibLogger.VerboseNewline("\tLooking for code reg (this might take a while)...");
671-
var codeReg = LibCpp2IlMain.MetadataVersion >= 24.2f ? searcher.FindCodeRegistrationPost2019() : searcher.FindCodeRegistrationPre2019();
675+
var codeReg = metadata.MetadataVersion >= 24.2f ? searcher.FindCodeRegistrationPost2019(metadata) : searcher.FindCodeRegistrationPre2019();
672676
LibLogger.VerboseNewline($"\tGot code reg 0x{codeReg:X}");
673677

674-
LibLogger.VerboseNewline($"\tLooking for meta reg ({(LibCpp2IlMain.MetadataVersion >= 27f ? "post-27" : "pre-27")})...");
675-
var metaReg = LibCpp2IlMain.MetadataVersion >= 27f ? searcher.FindMetadataRegistrationPost24_5() : searcher.FindMetadataRegistrationPre24_5();
678+
LibLogger.VerboseNewline($"\tLooking for meta reg ({(metadata.MetadataVersion >= 27f ? "post-27" : "pre-27")})...");
679+
var metaReg = metadata.MetadataVersion >= 27f ? searcher.FindMetadataRegistrationPost24_5(metadata) : searcher.FindMetadataRegistrationPre24_5();
676680
LibLogger.VerboseNewline($"\tGot meta reg 0x{metaReg:x}");
677681

678682
return (codeReg, metaReg);

LibCpp2IL/Il2CppBinary.cs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public abstract class Il2CppBinary(MemoryStream input) : ClassReadingBinaryReade
6262

6363
public int InBinaryMetadataSize { get; private set; }
6464

65-
public void Init(ulong pCodeRegistration, ulong pMetadataRegistration)
65+
public void Init(ulong pCodeRegistration, ulong pMetadataRegistration, Il2CppMetadata metadata)
6666
{
6767
var cr = pCodeRegistration > 0 ? ReadReadableAtVirtualAddress<Il2CppCodeRegistration>(pCodeRegistration) : null;
6868
var mr = pMetadataRegistration > 0 ? ReadReadableAtVirtualAddress<Il2CppMetadataRegistration>(pMetadataRegistration) : null;
@@ -112,7 +112,7 @@ public void Init(ulong pCodeRegistration, ulong pMetadataRegistration)
112112

113113
InBinaryMetadataSize += GetNumBytesReadSinceLastCallAndClear();
114114

115-
if (LibCpp2IlMain.MetadataVersion < 27)
115+
if (metadata.MetadataVersion < 27)
116116
{
117117
LibLogger.Verbose("\tReading custom attribute generators...");
118118
start = DateTime.Now;
@@ -161,7 +161,7 @@ public void Init(ulong pCodeRegistration, ulong pMetadataRegistration)
161161

162162
InBinaryMetadataSize += GetNumBytesReadSinceLastCallAndClear();
163163

164-
if (LibCpp2IlMain.MetadataVersion >= 24.2f)
164+
if (metadata.MetadataVersion >= 24.2f)
165165
{
166166
LibLogger.VerboseNewline("\tReading code gen modules...");
167167
start = DateTime.Now;
@@ -472,25 +472,28 @@ public virtual bool TryGetExportedFunctionName(ulong addr, [NotNullWhen(true)] o
472472

473473
public abstract ulong GetVirtualAddressOfPrimaryExecutableSection();
474474

475-
public virtual (ulong pCodeRegistration, ulong pMetadataRegistration) FindCodeAndMetadataReg(int methodCount, int typeDefinitionsCount)
475+
public virtual (ulong pCodeRegistration, ulong pMetadataRegistration) FindCodeAndMetadataReg(Il2CppMetadata metadata)
476476
{
477477
LibLogger.VerboseNewline("\tAttempting to locate code and metadata registration functions...");
478478

479+
var methodCount = metadata.methodDefs.Count(x => x.methodIndex >= 0);
480+
var typeDefinitionsCount = metadata.typeDefs.Length;
481+
479482
var plusSearch = new BinarySearcher(this, methodCount, typeDefinitionsCount);
480483

481484
LibLogger.VerboseNewline("\t\t-Searching for MetadataReg...");
482485

483-
var pMetadataRegistration = LibCpp2IlMain.MetadataVersion < 24.5f
486+
var pMetadataRegistration = metadata.MetadataVersion < 24.5f
484487
? plusSearch.FindMetadataRegistrationPre24_5()
485-
: plusSearch.FindMetadataRegistrationPost24_5();
488+
: plusSearch.FindMetadataRegistrationPost24_5(metadata);
486489

487490
LibLogger.VerboseNewline("\t\t-Searching for CodeReg...");
488491

489492
ulong pCodeRegistration;
490-
if (LibCpp2IlMain.MetadataVersion >= 24.2f)
493+
if (metadata.MetadataVersion >= 24.2f)
491494
{
492495
LibLogger.VerboseNewline("\t\t\tUsing mscorlib full-disassembly approach to get codereg, this may take a while...");
493-
pCodeRegistration = plusSearch.FindCodeRegistrationPost2019();
496+
pCodeRegistration = plusSearch.FindCodeRegistrationPost2019(metadata);
494497
}
495498
else
496499
pCodeRegistration = plusSearch.FindCodeRegistrationPre2019();

LibCpp2IL/LibCpp2IlBinaryRegistry.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,13 @@ internal static Il2CppBinary CreateAndInit(byte[] buffer, Il2CppMetadata metadat
6565

6666
LibCpp2IlMain.Binary = binary;
6767

68-
var (codereg, metareg) = binary.FindCodeAndMetadataReg(metadata.methodDefs.Count(x => x.methodIndex >= 0), metadata.typeDefs.Length);
68+
var (codereg, metareg) = binary.FindCodeAndMetadataReg(metadata);
6969

7070
LibLogger.InfoNewline($"Got Binary codereg: 0x{codereg:X}, metareg: 0x{metareg:X} in {(DateTime.Now - start).TotalMilliseconds:F0}ms.");
7171
LibLogger.InfoNewline("Initializing Binary...");
7272
start = DateTime.Now;
7373

74-
binary.Init(codereg, metareg);
74+
binary.Init(codereg, metareg, metadata);
7575

7676
LibLogger.InfoNewline($"Initialized Binary in {(DateTime.Now - start).TotalMilliseconds:F0}ms");
7777

LibCpp2IL/LibCpp2IlGlobalMapper.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ internal static void Reset()
3030

3131
internal static void MapGlobalIdentifiers(Il2CppMetadata metadata, Il2CppBinary cppAssembly)
3232
{
33-
if (LibCpp2IlMain.MetadataVersion < 27f)
33+
if (metadata.MetadataVersion < 27f)
3434
MapGlobalIdentifiersPre27(metadata, cppAssembly);
3535
else
3636
MapGlobalIdentifiersPost27(metadata, cppAssembly);

0 commit comments

Comments
 (0)