-
-
Notifications
You must be signed in to change notification settings - Fork 204
/
LibCpp2IlMain.cs
335 lines (264 loc) · 12.4 KB
/
LibCpp2IlMain.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using AssetRipper.Primitives;
using LibCpp2IL.Elf;
using LibCpp2IL.Logging;
using LibCpp2IL.Metadata;
using LibCpp2IL.NintendoSwitch;
using LibCpp2IL.Reflection;
using LibCpp2IL.Wasm;
namespace LibCpp2IL;
public static class LibCpp2IlMain
{
private static readonly Regex UnityVersionRegex = new Regex(@"^[0-9]+\.[0-9]+\.[0-9]+[abcfxp][0-9]+$", RegexOptions.Compiled);
public class LibCpp2IlSettings
{
public bool AllowManualMetadataAndCodeRegInput;
public bool DisableMethodPointerMapping;
public bool DisableGlobalResolving;
}
public static readonly LibCpp2IlSettings Settings = new();
public static bool Il2CppTypeHasNumMods5Bits;
public static float MetadataVersion = 24f;
public static Il2CppBinary? Binary;
public static Il2CppMetadata? TheMetadata;
public static readonly Dictionary<ulong, List<Il2CppMethodDefinition>> MethodsByPtr = new();
public static void Reset()
{
LibCpp2IlGlobalMapper.Reset();
MethodsByPtr.Clear();
}
public static List<Il2CppMethodDefinition>? GetManagedMethodImplementationsAtAddress(ulong addr)
{
MethodsByPtr.TryGetValue(addr, out var ret);
return ret;
}
public static MetadataUsage? GetAnyGlobalByAddress(ulong address)
{
if (MetadataVersion >= 27f)
return LibCpp2IlGlobalMapper.CheckForPost27GlobalAt(address);
//Pre-27
var glob = GetLiteralGlobalByAddress(address);
glob ??= GetMethodGlobalByAddress(address);
glob ??= GetRawFieldGlobalByAddress(address);
glob ??= GetRawTypeGlobalByAddress(address);
return glob;
}
public static MetadataUsage? GetLiteralGlobalByAddress(ulong address)
{
if (MetadataVersion < 27f)
return LibCpp2IlGlobalMapper.LiteralsByAddress.GetOrDefault(address);
return GetAnyGlobalByAddress(address);
}
public static string? GetLiteralByAddress(ulong address)
{
var literal = GetLiteralGlobalByAddress(address);
if (literal?.Type != MetadataUsageType.StringLiteral)
return null;
return literal.AsLiteral();
}
public static MetadataUsage? GetRawTypeGlobalByAddress(ulong address)
{
if (MetadataVersion < 27f)
return LibCpp2IlGlobalMapper.TypeRefsByAddress.GetOrDefault(address);
return GetAnyGlobalByAddress(address);
}
public static Il2CppTypeReflectionData? GetTypeGlobalByAddress(ulong address)
{
if (TheMetadata == null) return null;
var typeGlobal = GetRawTypeGlobalByAddress(address);
if (typeGlobal?.Type is not (MetadataUsageType.Type or MetadataUsageType.TypeInfo))
return null;
return typeGlobal.AsType();
}
public static MetadataUsage? GetRawFieldGlobalByAddress(ulong address)
{
if (MetadataVersion < 27f)
return LibCpp2IlGlobalMapper.FieldRefsByAddress.GetOrDefault(address);
return GetAnyGlobalByAddress(address);
}
public static Il2CppFieldDefinition? GetFieldGlobalByAddress(ulong address)
{
if (TheMetadata == null) return null;
var typeGlobal = GetRawFieldGlobalByAddress(address);
return typeGlobal?.AsField();
}
public static MetadataUsage? GetMethodGlobalByAddress(ulong address)
{
if (TheMetadata == null) return null;
if (MetadataVersion < 27f)
return LibCpp2IlGlobalMapper.MethodRefsByAddress.GetOrDefault(address);
return GetAnyGlobalByAddress(address);
}
public static Il2CppMethodDefinition? GetMethodDefinitionByGlobalAddress(ulong address)
{
var global = GetMethodGlobalByAddress(address);
if (global?.Type == MetadataUsageType.MethodRef)
return global.AsGenericMethodRef().BaseMethod;
return global?.AsMethod();
}
/// <summary>
/// Initialize the metadata and PE from a pair of byte arrays.
/// </summary>
/// <param name="binaryBytes">The content of the GameAssembly.dll file.</param>
/// <param name="metadataBytes">The content of the global-metadata.dat file</param>
/// <param name="unityVersion">The unity version</param>
/// <returns>True if the initialize succeeded, else false</returns>
/// <throws><see cref="System.FormatException"/> if the metadata is invalid (bad magic number, bad version), or if the PE is invalid (bad header signature, bad magic number)<br/></throws>
/// <throws><see cref="System.NotSupportedException"/> if the PE file specifies it is neither for AMD64 or i386 architecture</throws>
public static bool Initialize(byte[] binaryBytes, byte[] metadataBytes, UnityVersion unityVersion)
{
LibCpp2IlReflection.ResetCaches();
var start = DateTime.Now;
LibLogger.InfoNewline("Initializing Metadata...");
TheMetadata = Il2CppMetadata.ReadFrom(metadataBytes, unityVersion);
Il2CppTypeHasNumMods5Bits = MetadataVersion >= 27.2f;
if (TheMetadata == null)
return false;
LibLogger.InfoNewline($"Initialized Metadata in {(DateTime.Now - start).TotalMilliseconds:F0}ms");
Binary = LibCpp2IlBinaryRegistry.CreateAndInit(binaryBytes, TheMetadata);
if (!Settings.DisableGlobalResolving && MetadataVersion < 27)
{
start = DateTime.Now;
LibLogger.Info("Mapping Globals...");
LibCpp2IlGlobalMapper.MapGlobalIdentifiers(TheMetadata, Binary);
LibLogger.InfoNewline($"OK ({(DateTime.Now - start).TotalMilliseconds:F0}ms)");
}
if (!Settings.DisableMethodPointerMapping)
{
start = DateTime.Now;
LibLogger.Info("Mapping pointers to Il2CppMethodDefinitions...");
var i = 0;
foreach (var (method, ptr) in TheMetadata.methodDefs.Select(method => (method, ptr: method.MethodPointer)))
{
if (!MethodsByPtr.ContainsKey(ptr))
MethodsByPtr[ptr] = [];
MethodsByPtr[ptr].Add(method);
i++;
}
LibLogger.InfoNewline($"Processed {i} OK ({(DateTime.Now - start).TotalMilliseconds:F0}ms)");
}
LibCpp2IlReflection.InitCaches();
return true;
}
/// <summary>
/// Initialize the metadata and PE from their respective file locations.
/// </summary>
/// <param name="pePath">The path to the GameAssembly.dll file</param>
/// <param name="metadataPath">The path to the global-metadata.dat file</param>
/// <param name="unityVersion">The unity version, split on periods, with the patch version (e.g. f1) stripped out. For example, [2018, 2, 0]</param>
/// <returns>True if the initialize succeeded, else false</returns>
/// <throws><see cref="System.FormatException"/> if the metadata is invalid (bad magic number, bad version), or if the PE is invalid (bad header signature, bad magic number)<br/></throws>
/// <throws><see cref="System.NotSupportedException"/> if the PE file specifies it is neither for AMD64 or i386 architecture</throws>
public static bool LoadFromFile(string pePath, string metadataPath, UnityVersion unityVersion)
{
var metadataBytes = File.ReadAllBytes(metadataPath);
var peBytes = File.ReadAllBytes(pePath);
return Initialize(peBytes, metadataBytes, unityVersion);
}
/// <summary>
/// Attempts to determine the Unity version from the given binary path and game data path
/// </summary>
/// <param name="unityPlayerPath">The path to the unity player executable - either the executable itself or [lib]unityplayer[.dll]</param>
/// <param name="gameDataPath">The path to the GameName_Data folder, from which assets files can be read.</param>
/// <returns>A valid unity version if one can be read, else 0.0.0a0</returns>
public static UnityVersion DetermineUnityVersion(string? unityPlayerPath, string? gameDataPath)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT && !string.IsNullOrEmpty(unityPlayerPath))
{
LibLogger.VerboseNewline($"DetermineUnityVersion: Running on windows so have FileVersionInfo, trying to pull version from unity player {unityPlayerPath}");
var unityVer = FileVersionInfo.GetVersionInfo(unityPlayerPath);
if (unityVer.FileMajorPart > 0)
return new UnityVersion((ushort)unityVer.FileMajorPart, (ushort)unityVer.FileMinorPart, (ushort)unityVer.FileBuildPart);
LibLogger.VerboseNewline($"DetermineUnityVersion: FileVersionInfo gave useless result, falling back to other methods");
}
if (!string.IsNullOrEmpty(gameDataPath))
{
LibLogger.VerboseNewline($"DetermineUnityVersion: Have game data path {gameDataPath}, trying to pull version from globalgamemanagers or data.unity3d");
//Globalgamemanagers
var globalgamemanagersPath = Path.Combine(gameDataPath, "globalgamemanagers");
if (File.Exists(globalgamemanagersPath))
{
LibLogger.VerboseNewline($"DetermineUnityVersion: globalgamemanagers exists, pulling version from it");
var ggmBytes = File.ReadAllBytes(globalgamemanagersPath);
return GetVersionFromGlobalGameManagers(ggmBytes);
}
//Data.unity3d
var dataPath = Path.Combine(gameDataPath, "data.unity3d");
if (File.Exists(dataPath))
{
LibLogger.VerboseNewline($"DetermineUnityVersion: data.unity3d exists, pulling version from it");
using var dataStream = File.OpenRead(dataPath);
return GetVersionFromDataUnity3D(dataStream);
}
LibLogger.VerboseNewline($"DetermineUnityVersion: No globalgamemanagers or data.unity3d found in game data path.");
}
LibLogger.VerboseNewline($"DetermineUnityVersion: All methods to determine unity version failed!");
return default;
}
/// <summary>
/// Attempts to determine the Unity version from the given globalgamemanagers file
/// </summary>
/// <param name="ggmBytes">The bytes making up the globalgamemanagers asset file</param>
/// <returns>A valid unity version if one can be read, else 0.0.0a0</returns>
public static UnityVersion GetVersionFromGlobalGameManagers(byte[] ggmBytes)
{
var verString = new StringBuilder();
var idx = 0x14;
while (ggmBytes[idx] != 0)
{
verString.Append(Convert.ToChar(ggmBytes[idx]));
idx++;
}
string unityVer = verString.ToString();
if (!UnityVersionRegex.IsMatch(unityVer))
{
idx = 0x30;
verString = new StringBuilder();
while (ggmBytes[idx] != 0)
{
verString.Append(Convert.ToChar(ggmBytes[idx]));
idx++;
}
unityVer = verString.ToString().Trim();
}
return UnityVersion.Parse(unityVer);
}
/// <summary>
/// Attempts to determine the Unity version from the given data.unity3d file
/// </summary>
/// <param name="fileStream">A stream referencing the data.unity3d file. A stream is used instead of a byte array because these files can be very large. Only the first 30-or-so bytes are used.</param>
/// <returns>A valid unity version if one can be read, else 0.0.0a0</returns>
public static UnityVersion GetVersionFromDataUnity3D(Stream fileStream)
{
//data.unity3d is a bundle file and it's used on later unity versions.
//These files are usually really large and we only want the first couple bytes, so it's done via a stream.
//e.g.: Secret Neighbour
//Fake unity version at 0xC, real one at 0x12
var verString = new StringBuilder();
if (fileStream.CanSeek)
fileStream.Seek(0x12, SeekOrigin.Begin);
else
{
if (fileStream.Read(new byte[0x12], 0, 0x12) != 0x12)
throw new("Failed to seek to 0x12 in data.unity3d");
}
while (true)
{
var read = fileStream.ReadByte();
if (read == 0)
{
//I'm using a while true..break for this, shoot me.
break;
}
verString.Append(Convert.ToChar(read));
}
var unityVer = verString.ToString().Trim();
return UnityVersion.Parse(unityVer);
}
}