-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerialisationHandler.cs
845 lines (684 loc) · 34.7 KB
/
SerialisationHandler.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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.Class;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.MethodInfo;
using UnityEngine;
using static FieldInjector.Util;
using static MelonLoader.MelonLogger;
using static Il2CppInterop.Runtime.Runtime.UnityVersionHandler;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime;
using MelonLoader.NativeUtils;
using System.Runtime.CompilerServices;
namespace FieldInjector
{
public static unsafe class SerialisationHandler
{
#region Simple Action<IntPtr> Invoker
private static readonly IntPtr invokerPtr;
static SerialisationHandler()
{
var del = new InvokerDelegate(StaticVoidIntPtrInvoker);
GCHandle.Alloc(del, GCHandleType.Normal); // prevent GC of our delegate
invokerPtr = Marshal.GetFunctionPointerForDelegate(del);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr InvokerDelegate(IntPtr methodPointer, Il2CppMethodInfo* methodInfo, IntPtr obj, IntPtr* args);
private delegate void StaticVoidIntPtrDelegate(IntPtr intPtr);
private static IntPtr StaticVoidIntPtrInvoker(IntPtr methodPointer, Il2CppMethodInfo* methodInfo, IntPtr obj, IntPtr* args)
{
Marshal.GetDelegateForFunctionPointer<StaticVoidIntPtrDelegate>(methodPointer)(obj);
return IntPtr.Zero;
}
#endregion Simple Action<IntPtr> Invoker
#region Injection Entrypoint and Dependency processing
private static bool IsTypeInjected(Type t)
{
return GetClassPointerForType(t) != IntPtr.Zero;
}
public static void Inject<T>(int debugLevel = 0)
{
Inject(debugLevel, typeof(T));
}
public static void Inject(Type type, int debugLevel = 0)
{
Inject(debugLevel, type);
}
public static void Inject(int debugLevel = 0, params Type[] t)
{
LogLevel = debugLevel;
var typesToInject = new HashSet<Type>();
Type ProcessType(Type ft)
{
if (ft.IsEnum) ft = ft.GetEnumUnderlyingType();
if (ft.IsPrimitive) return null;
if (typesToInject.Contains(ft)) return null;
if (ft.IsArray) return ProcessType(ft.GetElementType());
if (ft.IsGenericType)
{
var td = ft.GetGenericTypeDefinition();
if (td == typeof(List<>) || td == typeof(Nullable)) return ProcessType(ft.GetGenericArguments()[0]);
}
if (IsTypeInjected(ft)) return null;
return ft;
}
void CollectDependencies(Type ct)
{
if (ct == null) return;
if (serialisationCache.ContainsKey(ct)) { return; }
if (typesToInject.Contains(ct)) { return; }
typesToInject.Add(ct);
if (!ct.IsValueType && ct.BaseType != null) CollectDependencies(ProcessType(ct.BaseType));
foreach (var type in ct
.GetFields(BindingFlags.Instance | BindingFlags.Public)
.Where(field => !field.IsNotSerialized)
.Select((field) => ProcessType(field.FieldType))
.Where(r => r != null))
{
CollectDependencies(type);
}
}
foreach (var type in t) CollectDependencies(ProcessType(type));
int numClasses = 0, numStructs = 0;
foreach (var tti in typesToInject)
{
if (tti.IsValueType) { numStructs++; }
else { numClasses++; }
}
Type[] classes = new Type[numClasses];
Type[] structs = new Type[numStructs];
int icl = 0, ist = 0;
foreach (var type in typesToInject)
{
if (!type.IsValueType) { classes[icl++] = type; }
else { structs[ist++] = type; }
}
InjectBatch(classes, structs);
}
private struct InjectionProgress
{
public bool Failed;
public MyIl2CppClass* ClassPtr;
public SerialisedField[] Result;
}
private static readonly Dictionary<Type, InjectionProgress> injection = new Dictionary<Type, InjectionProgress>();
#endregion Injection Entrypoint and Dependency processing
#region Fake Images / Tokens
// unhollower assigns fake tokens descending by starting at -2 (il2cpp only uses positive tokens, so the all the negative numbers can be used by us safely
// we used to use a publiciser to allocate them with unhollower's ones, so we decremented their counter
// however to avoid hooking into unhollower's gubbins too much we can just start at the other end of the negative numbers
// and if someone injects enough types for them to meet then the universe has literally exploded
private static long myTokenOverride = long.MinValue + 1;
private static ConcurrentDictionary<long, IntPtr> _fakeTokenClasses;
internal static IntPtr _fakeImage;
private static IntPtr _fakeAssembly;
private static bool _initImage;
internal static Dictionary<Type, IntPtr> _injectedStructs = new Dictionary<Type, IntPtr>();
private static Action<Type, IntPtr> AddTypeToLookup = (Action<Type, IntPtr>)Delegate.CreateDelegate(typeof(Action<Type, IntPtr>), HarmonyLib.AccessTools.Method("Il2CppInterop.Runtime.Injection.InjectorHelpers:AddTypeToLookup", parameters: new Type[] { typeof(Type), typeof(IntPtr) }));
private delegate IntPtr GetManagerFromContextDelegate(int index);
internal static void InitImage()
{
if (_initImage) return;
// largely does a similar thing to unhollower
var img = NewImage();
var asm = NewAssembly();
var name = Marshal.StringToHGlobalAnsi("InjectedStructs");
asm.Name.Name = name;
img.Assembly = asm.AssemblyPointer;
img.Dynamic = 1;
img.Name = name;
if (img.HasNameNoExt)
{
img.NameNoExt = img.Name;
}
_fakeImage = img.Pointer;
_fakeAssembly = asm.Pointer;
_initImage = true;
// time for the hack to add our image to the script managers image list
// struct injection won't work if it isn't in there
IntPtr codePtr = IL2CPP.il2cpp_resolve_icall("UnityEngine.LayerMask::LayerToName");
var getTagManager = XrefScannerLowLevelCustom.JumpTargets(codePtr).First();
var getManagerFromContext = XrefScannerLowLevelCustom.JumpTargets(getTagManager).Single();
var getmanager = Marshal.GetDelegateForFunctionPointer<GetManagerFromContextDelegate>(getManagerFromContext);
var scriptingManager = getmanager(5); // we got the scripting manager!
var scriptImages = scriptingManager + 0x228; // here we gooooooo
var array = (DynamicArrayOfPtrs*)scriptImages;
array->InsertReplaceNull(_fakeImage); // hope there's a blank spot in there for us!
Log($"Added fake image to script manager: 0x{(ulong)_fakeImage:X}, new size {array->size}", 2);
}
private static IntPtr FakeImage
{
get
{
if (!_initImage) InitImage();
return _fakeImage;
}
}
private static IntPtr FakeAssembly
{
get
{
if (!_initImage) InitImage();
return _fakeAssembly;
}
}
private static ConcurrentDictionary<long, IntPtr> FakeTokenClasses
{
get
{
_fakeTokenClasses ??= HarmonyLib.AccessTools.Field("Il2CppInterop.Runtime.Injection.InjectorHelpers:s_InjectedClasses")?.GetValue(null) as ConcurrentDictionary<long, IntPtr> ?? throw new Exception("Can't find fake token classes dictionary");
return _fakeTokenClasses;
}
}
#endregion Fake Images / Tokens
#region Main Serialiser
private static IntPtr InjectStruct(Type type)
{
HookGetTypeInfo();
IntPtr result = GetClassPointerForType(type);
if (result != IntPtr.Zero) { return result; }
if (type.IsGenericType || type.IsEnum || !type.IsValueType)
{
throw new InvalidOperationException($"Type {type} is not valid for struct injection");
}
var basePtr = GetClassPointerForType<Il2CppSystem.ValueType>();
var baseKlass = (MyIl2CppClass*)basePtr;
// allocate class pointer
var p = (MyIl2CppClass*)NewClass(baseKlass->vtable_count).Pointer;
// assign token, set it to lead to our class
long token = Interlocked.Increment(ref myTokenOverride);
FakeTokenClasses[token] = (IntPtr)p;
// start setting up our class properties, mostly referenced from dumped il2cpp structs or unhollower classinjector
p->image = (Il2CppImage*)FakeImage;
p->gc_desc = IntPtr.Zero;
p->name = Marshal.StringToHGlobalAnsi(type.Name);
p->namespaze = Marshal.StringToHGlobalAnsi(type.Namespace ?? string.Empty);
p->byval_arg = new MyIl2CppType()
{
data = (IntPtr)token,
attrs = 0,
type = Il2CppTypeEnum.IL2CPP_TYPE_VALUETYPE,
num_mods = 0,
byref = false,
pinned = false,
valuetype = true,
};
p->this_arg = new MyIl2CppType()
{
data = (IntPtr)token,
attrs = 0,
type = Il2CppTypeEnum.IL2CPP_TYPE_VALUETYPE,
num_mods = 0,
byref = true,
pinned = false,
valuetype = false,
};
p->element_class = (Il2CppClass*)p;
p->castClass = (Il2CppClass*)p;
p->declaringType = (Il2CppClass*)IntPtr.Zero;
p->parent = (Il2CppClass*)basePtr;
p->generic_class = IntPtr.Zero;
p->typeDefinition = (IntPtr)token;
p->interopData = IntPtr.Zero;
p->klass = (Il2CppClass*)p;
p->events = (Il2CppEventInfo*)IntPtr.Zero;
p->event_count = 0;
p->properties = (Il2CppPropertyInfo*)IntPtr.Zero;
p->property_count = 0;
// todo-ish : field methods not injected
p->methods = baseKlass->methods;
p->method_count = baseKlass->method_count;
p->nestedTypes = (Il2CppClass**)IntPtr.Zero;
p->nested_type_count = 0;
// no interfaces, fine for now I guess, can rework if needed
p->implementedInterfaces = (Il2CppClass**)IntPtr.Zero;
p->interfaces_count = 0;
p->interfaceOffsets = (Il2CppRuntimeInterfaceOffsetPair*)IntPtr.Zero;
p->interface_offsets_count = 0;
// nope lol
p->static_fields = IntPtr.Zero;
p->static_fields_size = 0;
p->thread_static_fields_size = 0;
p->thread_static_fields_offset = 0;
p->rgctx_data = IntPtr.Zero;
// build type heirachy
var typeDepth = baseKlass->typeHierarchyDepth + 1;
p->typeHierarchyDepth = (byte)typeDepth;
p->typeHierarchy = (Il2CppClass**)Marshal.AllocHGlobal(typeDepth * IntPtr.Size);
p->typeHierarchy[typeDepth - 1] = (Il2CppClass*)basePtr;
for (int i = 0; i < typeDepth; i++)
{
p->typeHierarchy[i] = baseKlass->typeHierarchy[i];
}
p->unity_user_data = IntPtr.Zero;
p->initializationExceptionGCHandle = 0;
// setting these to 1 so it doesn't try any funny business I guess? won't hurt, probably won't do anything
p->cctor_started = 1;
p->cctor_finished = 1;
p->native_size = 0;
p->instance_size = (uint)sizeof(Il2CppObject);
p->actualSize = (uint)sizeof(Il2CppObject);
p->genericContainerIndex = IntPtr.Zero;
p->element_size = 0;
p->token = 0; // il2cpp doesn't seem to care about this
p->vtable_count = baseKlass->vtable_count;
p->genericRecursionDepth = 1;
p->rank = 0;
p->flags = Il2CppClassAttributes.TYPE_ATTRIBUTE_PUBLIC | Il2CppClassAttributes.TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT | Il2CppClassAttributes.TYPE_ATTRIBUTE_SEALED | Il2CppClassAttributes.TYPE_ATTRIBUTE_SERIALIZABLE;
p->minimumAlignment = 8;
p->naturalAligment = 8;
p->packingSize = 0;
p->bitfield =
MyIl2CppClass.ClassFlags.initialized_and_no_error
| MyIl2CppClass.ClassFlags.initialized
| MyIl2CppClass.ClassFlags.is_vtable_initialized;
var vtablePtr = (VirtualInvokeData*)Wrap((Il2CppClass*)p).VTable;
var parentVtablePtr = (VirtualInvokeData*)Wrap((Il2CppClass*)basePtr).VTable;
for (int i = 0; i < baseKlass->vtable_count; i++)
{
vtablePtr[i] = parentVtablePtr[i];
Log($"vtablePtr = {(IntPtr)(vtablePtr + i)}", 5);
Log($"vtablePtr method = {(IntPtr)vtablePtr[i].method}", 5);
if (vtablePtr[i].method != null) Log($"copying vtable {Marshal.PtrToStringAnsi(Wrap(vtablePtr[i].method).Name)}", 5);
}
AddTypeToLookup(type, (IntPtr)p);
_injectedStructs[type] = (IntPtr)p;
RuntimeSpecificsStore.SetClassInfo((IntPtr)p, true);
SetClassPointerForType(type, (IntPtr)p);
return (IntPtr)p;
}
private static void InjectStructFields(Type type, MyIl2CppClass* klass)
{
var serialiser = StructSerialiser<float>.GetSerialiser(type);
if (serialiser.IsBlittable)
{
klass->bitfield |= MyIl2CppClass.ClassFlags.is_blittable;
}
serialiser.WriteFields(klass);
}
private static void InjectBatch(Type[] classes, Type[] structs)
{
injection.Clear();
int n = classes.Length;
int m = structs.Length;
// build a mapping of the structs and their dependencies
Dictionary<Type, List<Type>> structDependencyMappings = new Dictionary<Type, List<Type>>();
foreach (var type in structs)
{
List<Type> list = null;
foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
if (field.IsNotSerialized) { continue; }
if (structs.Contains(field.FieldType))
{
if (list == null) { list = new List<Type>(); }
list.Add(field.FieldType);
}
}
if (list != null) { structDependencyMappings.Add(type, list); }
}
// reorder the list to ensure that structs that are inside other structs are injected before those structs
for (int i = 0; i < m; i++)
{
if (structDependencyMappings.TryGetValue(structs[i], out var dependencies))
{
foreach (var dep in dependencies)
{
int j = Array.IndexOf(structs, dep);
if (j > i) // the dependency needs to be before the dependent, so swap
{
(structs[i], structs[j]) = (structs[j], structs[i]);
i--; // this will set us back so we now check the dependency we just swapped into this slot on the next iteration
break;
}
}
}
}
// reorder the list to ensure that base types are processed first
for (int i = 0; i < n; i++)
{
int index = Array.IndexOf(classes, classes[i].BaseType);
if (index != -1 && index < i)
{
// swap
(classes[i], classes[index]) = (classes[index], classes[i]);
}
}
Log($"Serialising a batch of {n} classes and {m} structs:", 1);
if (LogLevel >= 1)
{
foreach (var tti in structs) Msg($" {tti.FullName}");
foreach (var tti in classes) Msg($" {tti.FullName}");
}
// Initial struct injection
IntPtr[] structPtrs = new IntPtr[m];
for (int i = 0; i < m; i++)
{
Type t = structs[i];
try
{
Log($"Initial injection for struct {t.Name}", 2);
structPtrs[i] = InjectStruct(t);
Log($"Struct {t.Name} injected at 0x{(ulong)structPtrs[i]:X}", 3);
}
catch (Exception ex)
{
Error($"Struct initial injection failed for {t}:", ex);
}
}
// Inject class and get a reference to it.
foreach (var t in classes)
{
try
{
Log($"Initial injection for {t.Name}", 2);
ClassInjector.RegisterTypeInIl2Cpp(t, new RegisterTypeOptions()
{
Interfaces = new Type[] { typeof(ISerializationCallbackReceiver) },
});
Log($"Get ptr for {t.Name}", 3);
var klassPtr = (MyIl2CppClass*)GetClassPointerForType(t, bypassEnums: true);
var klass = Wrap((Il2CppClass*)klassPtr);
// fix for unhollower not setting namespace field if there's no namespace
if (klassPtr->namespaze == IntPtr.Zero)
{
klassPtr->namespaze = Marshal.StringToHGlobalAnsi(string.Empty);
}
// fix Finalizer so it doesn't crash
FixFinaliser(klass);
injection[t] = new InjectionProgress()
{
Failed = false,
ClassPtr = klassPtr,
};
}
catch (Exception ex)
{
Log($"Failed to do initial injection on type {t.Name}: {ex}", 0);
injection[t] = new InjectionProgress()
{
Failed = true,
};
}
}
// Inject struct fields
for (int i = 0; i < m; i++)
{
var t = structs[i];
try
{
Log($"Writing struct fields for {t.FullName}", 2);
var p = structPtrs[i];
InjectStructFields(t, (MyIl2CppClass*)p);
}
catch (Exception ex)
{
Error($"Struct field injection failed for {t}:", ex);
}
}
// Inject class fields
foreach (var t in classes)
{
var inj = injection[t];
try
{
Log($"Start field injection for {t.Name}", 3);
var klassPtr = inj.ClassPtr;
var klass = Wrap((Il2CppClass*)klassPtr);
var baseKlassPtr = (MyIl2CppClass*)GetClassPointerForType(t.BaseType);
Log($"Initial field serialisation for {t.Name}", 4);
// Select serialisable fields, make serialiser classes.
var bflags = BindingFlags.Instance | BindingFlags.DeclaredOnly;
SerialisedField[] injectedFields =
t.GetFields(bflags | BindingFlags.Public)
.Where(field => !field.IsNotSerialized)
.Select(field => TrySerialise(field))
.Where(field => field != null)
.ToArray();
Log($"Finding base fields for {t.Name}", 3);
SerialisedField[] baseFields = null;
if (injection.TryGetValue(t.BaseType, out var baseInj))
{
baseFields = baseInj.Result;
}
else serialisationCache.TryGetValue(t.BaseType, out baseFields);
Log($"Compiling fields for {t.Name}", 4);
int numBaseFields = baseFields?.Length ?? 0;
SerialisedField[] allFields = new SerialisedField[numBaseFields + injectedFields.Length];
baseFields?.CopyTo(allFields, 0);
injectedFields.CopyTo(allFields, numBaseFields);
// Unhollower uses the last IntPtr of a class for a GCHandle of the managed object - we inject fields before this
int offset = (int)klass.ActualSize - IntPtr.Size;
Log($"Allocating field info for {t.Name}", 4);
// Allocate and fill fields array
var fieldsStore = (MyIl2CppFieldInfo*)Marshal.AllocHGlobal(allFields.Length * Marshal.SizeOf(typeof(MyIl2CppFieldInfo)));
// Copy base fields
for (int i = 0; i < numBaseFields; i++)
{
fieldsStore[i] = baseKlassPtr->fields[i];
}
// Create new fields
for (int i = 0; i < injectedFields.Length; i++)
{
var field = injectedFields[i];
Log($"[{offset}] Converting field {field.ManagedField} as {field}", 2);
var nativeField = Wrap((Il2CppFieldInfo*)(fieldsStore + numBaseFields + i));
field.FillFieldInfoStruct(nativeField, (Il2CppClass*)klassPtr, ref offset);
field.NativeField = nativeField.Pointer;
}
// Assign the field array
klassPtr->field_count = (ushort)allFields.Length;
klassPtr->fields = fieldsStore;
Log($"Injected {injectedFields.Length} fields (for a total of {allFields.Length}), changing class size from {klass.ActualSize} to {offset + IntPtr.Size}", 2);
// Reassign our new size, remembering the last IntPtr.
klass.ActualSize = klass.InstanceSize = (uint)(offset + IntPtr.Size);
klassPtr->gc_desc = IntPtr.Zero;
// Preparing to do serialisation - find some info about the ISerializationCallbackReceiver
Il2CppClass* callbackRecieverClass = (Il2CppClass*)Il2CppClassPointerStore<ISerializationCallbackReceiver>.NativeClassPtr;
var iface = Wrap(callbackRecieverClass);
int interfaceIndex = 0;
for (; interfaceIndex < klass.InterfaceCount; interfaceIndex++)
{
if (klass.ImplementedInterfaces[interfaceIndex] == callbackRecieverClass)
{
break;
}
}
if (interfaceIndex == klass.InterfaceCount)
{
throw new InvalidOperationException("Could not find serialisation callbacks interface!");
}
if (interfaceIndex >= klass.InterfaceOffsetsCount)
{
throw new InvalidOperationException("interface is >= interface offsets count!");
}
int interfaceOffset = klass.InterfaceOffsets[interfaceIndex].offset;
// Now create the serialisation methods - this code is common to both
var nativePtr = Expression.Parameter(typeof(IntPtr), "nativeObjPtr");
var managedObj = Expression.Variable(t, "managedObj");
var fieldPtr = Expression.Variable(typeof(IntPtr), "fieldPtr");
MethodInfo getMonoObjectMethod = ((Func<IntPtr, object>)ClassInjectorBase.GetMonoObjectFromIl2CppPointer).Method;
MethodInfo getGCHandleMethod = ((Func<IntPtr, IntPtr>)ClassInjectorBase.GetGcHandlePtrFromIl2CppObject).Method;
Expression[] setupExpressions = new Expression[]
{
// managedObj = ClassInjectorBase.GetMonoObjectFromIl2CppPointer(nativeObjPtr);
Expression.Assign(managedObj,
Expression.Convert(
Expression.Call(getMonoObjectMethod, nativePtr),
t)),
};
// Create and inject the deserialiser
var expressions = setupExpressions
.Concat(
allFields
.SelectMany(field => field.GetDeserialiseExpression(managedObj, nativePtr, fieldPtr))
);
if (LogLevel >= 3)
{
expressions = expressions.Prepend(LogExpression($"Deserialise {t}:", nativePtr));
expressions = expressions.Append(LogExpression("Deserialise complete: ", nativePtr));
}
var deserialiseExpression = Expression.Block(
new ParameterExpression[] { managedObj, fieldPtr },
expressions);
Log($"Generated deserialiser method:\n{string.Join("\n", deserialiseExpression.Expressions)}", 3);
var deserialiseMethod = Expression.Lambda<StaticVoidIntPtrDelegate>(deserialiseExpression, nativePtr);
EmitSerialiserMethod(deserialiseMethod, t, klass, nameof(ISerializationCallbackReceiver.OnAfterDeserialize), iface, interfaceOffset, LogLevel);
// Now the serialiser
expressions = setupExpressions.Concat(
allFields
.SelectMany(field => field.GetSerialiseExpression(managedObj, nativePtr)));
if (LogLevel >= 3)
{
expressions = expressions.Prepend(LogExpression($"Serialise {t}:", nativePtr));
expressions = expressions.Append(LogExpression("Serialise complete: ", nativePtr));
}
var serialiseExpression = Expression.Block(
new ParameterExpression[] { managedObj },
expressions);
Log($"Generated serialiser method: \n{string.Join("\n", serialiseExpression.Expressions)}", 3);
var serialiseMethod = Expression.Lambda<StaticVoidIntPtrDelegate>(serialiseExpression, nativePtr);
EmitSerialiserMethod(serialiseMethod, t, klass, nameof(ISerializationCallbackReceiver.OnBeforeSerialize), iface, interfaceOffset, LogLevel);
serialisationCache[t] = allFields;
Log($"Completed serialisation injection for type {t}", 2);
}
catch (Exception ex)
{
Log($"Failed to do field injection on type {t.Name}: {ex}", 0);
inj.Failed = true;
}
injection[t] = inj;
}
}
private static readonly Dictionary<Type, SerialisedField[]> serialisationCache = new Dictionary<Type, SerialisedField[]>();
private static void FixFinaliser(INativeClassStruct klass)
{
if (klass.HasFinalize)
{
var method = Wrap(klass.Methods[0]);
method.MethodPointer = Marshal.GetFunctionPointerForDelegate(FinalizeDelegate);
method.InvokerMethod = invokerPtr;
}
}
private static void EmitSerialiserMethod(LambdaExpression lambda, Type monoType, INativeClassStruct klass, string name, INativeClassStruct iface, int interfaceOffset, int debugLevel)
{
// Find the VTable slot for our element, and the original interface method
VirtualInvokeData* vtableElement = default;
INativeMethodInfoStruct ifaceMethod = default;
VirtualInvokeData* vtablePtr = (VirtualInvokeData*)klass.VTable;
for (int i = 0; i < iface.MethodCount; i++)
{
ifaceMethod = Wrap(iface.Methods[i]);
if (Marshal.PtrToStringAnsi(ifaceMethod.Name) == name)
{
vtableElement = vtablePtr + (i + interfaceOffset);
if (debugLevel > 3)
{
Msg($"Injecting {name} in vtable slot {i + interfaceOffset}");
}
break;
}
}
if (vtablePtr == default)
{
throw new InvalidOperationException($"Can't find interface method {name}");
}
var compiledDelegate = lambda.Compile();
GCHandle.Alloc(compiledDelegate, GCHandleType.Normal); // no more GC!
var generated = NewMethod();
generated.Name = Marshal.StringToHGlobalAnsi(name);
generated.Class = klass.ClassPointer;
generated.ReturnType = ifaceMethod.ReturnType;
generated.Flags = Il2CppMethodFlags.METHOD_ATTRIBUTE_PUBLIC | Il2CppMethodFlags.METHOD_ATTRIBUTE_HIDE_BY_SIG;
generated.InvokerMethod = invokerPtr;
generated.MethodPointer = Marshal.GetFunctionPointerForDelegate(compiledDelegate);
vtableElement->method = generated.MethodInfoPointer;
vtableElement->methodPtr = generated.MethodPointer;
}
private static SerialisedField TrySerialise(FieldInfo field)
{
try
{
var res = SerialisedField.InferFromField(field);
Log($"Created field of type {res.GetType().Name} for field {field.FieldType.Name} {field.Name}", 5);
return res;
}
catch (Exception ex)
{
Warning($"Not serialising field {field} due to error: {ex.Message}\n{ex.StackTrace}");
}
return null;
}
#endregion Main Serialiser
#region Finalize patch
private static readonly StaticVoidIntPtrDelegate FinalizeDelegate = Finalize;
private static void Finalize(IntPtr ptr)
{
var gcHandle = ClassInjectorBase.GetGcHandlePtrFromIl2CppObject(ptr);
if (gcHandle == IntPtr.Zero) { return; }
GCHandle.FromIntPtr(gcHandle).Free();
}
#endregion Finalize patch
#region Hook GetClassOrElementClass
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate MyIl2CppClass* GetTypeInfoFromTypeDelegate(MyIl2CppType* type);
private static NativeHook<GetTypeInfoFromTypeDelegate> getTypeInfoHook;
private static bool _typeInfoPatched = false;
[UnmanagedCallersOnly(CallConvs = new Type[] { typeof(CallConvCdecl) })]
private static unsafe MyIl2CppClass* GetTypeInfoFromTypePatch(MyIl2CppType* type)
{
if (type->type == Il2CppTypeEnum.IL2CPP_TYPE_VALUETYPE || type->type == Il2CppTypeEnum.IL2CPP_TYPE_CLASS)
{
if (_fakeTokenClasses.TryGetValue((long)type->data, out var classPtr))
{
return (MyIl2CppClass*)classPtr;
}
}
while (getTypeInfoHook == null)
{
Thread.Sleep(1);
}
return getTypeInfoHook.Trampoline(type);
}
private static void HookGetTypeInfo()
{
if (_typeInfoPatched) return;
_typeInfoPatched = true;
Log("Patching get type from info", 3);
var ga = LoadLibrary("GameAssembly.dll");
var class_from_type = GetProcAddress(ga, nameof(IL2CPP.il2cpp_class_from_il2cpp_type));
var get_class_or_element_class = GetProcAddress(ga, nameof(IL2CPP.il2cpp_type_get_class_or_element_class));
// Il2CppClass * Class::FromIl2CppType(Il2CppType *type,bool throwOnError)
var classFromType = XrefScannerLowLevelCustom.JumpTargets(class_from_type).Single();
Log($"classFromType = 0x{(ulong)classFromType:X}", 4);
// Il2CppClass* Type::GetClassOrElementClass(Il2CppType* type)
var getClassOrElementClass = XrefScannerLowLevelCustom.JumpTargets(get_class_or_element_class).Single();
Log($"getClassOrElementClass = 0x{(ulong)getClassOrElementClass:X}", 4);
// Il2CppClass* MetadataCache::GetTypeInfoFromType(Il2CppType* type)
Log($"jumptargets: {string.Join(", ", XrefScannerLowLevelCustom.JumpTargets(getClassOrElementClass).Select(p => ((long)p).ToString("X")))}", 5);
var cacheGetTypeInfoFromType = (from tgt in XrefScannerLowLevelCustom.JumpTargets(getClassOrElementClass)
where tgt != classFromType
select tgt).Single();
Log($"cacheGetTypeInfoFromType = 0x{(ulong)cacheGetTypeInfoFromType:X}", 4);
// Il2CppClass* GlobalMetadata::GetTypeInfoFromType(Il2CppClass* type)
var metadataGetTypeInfoFromType = XrefScannerLowLevelCustom.JumpTargets(cacheGetTypeInfoFromType).Single();
Log($"metadataGetTypeInfoFromType = 0x{(ulong)metadataGetTypeInfoFromType:X}", 4);
// MyIl2CppClass* GetTypeInfoFromTypeDelegate(MyIl2CppType* type)
delegate* unmanaged[Cdecl]<MyIl2CppType*, MyIl2CppClass*> fp = &GetTypeInfoFromTypePatch;
getTypeInfoHook = new(metadataGetTypeInfoFromType, (IntPtr)fp);
getTypeInfoHook.Attach();
}
#endregion Hook GetClassOrElementClass
}
}