-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathMetadata.cs
885 lines (816 loc) · 32.4 KB
/
Metadata.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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Security.Cryptography;
using Ether_IL2CPP;
using System.IO;
namespace Ether_IL2CPP
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
class VersionAttribute : Attribute
{
public double Min { get; set; } = 0;
public double Max { get; set; } = 99;
}
[AttributeUsage(AttributeTargets.Field)]
class ArrayLengthAttribute : Attribute
{
public int Length { get; set; }
}
public class StringLiteral
{
public uint Length;
public uint Offset;
}
public class ImageDefinition
{
public uint nameIndex;
public int assemblyIndex;
public int typeStart;
public uint typeCount;
public int exportedTypeStart;
public uint exportedTypeCount;
public int entryPointIndex;
public uint token;
public int customAttributeStart;
public uint customAttributeCount;
}
public class Il2CppAssemblyDefinition
{
public int imageIndex;
public uint token;
public int referencedAssemblyStart;
public int referencedAssemblyCount;
public Il2CppAssemblyNameDefinition aname;
}
public class Il2CppAssemblyNameDefinition
{
public int nameIndex;
public int cultureIndex;
public int publicKeyIndex;
public uint hash_alg;
public int hash_len;
public uint flags;
public int major;
public int minor;
public int build;
public int revision;
[ArrayLength(Length = 8)]
public byte[] public_key_token;
}
public class Il2CppWindowsRuntimeTypeNamePair
{
public int nameIndex;
public int typeIndex;
}
public class Il2CppTypeDefinition
{
public uint nameIndex;
public uint namespaceIndex;
public int byvalTypeIndex;
public int byrefTypeIndex;
public int declaringTypeIndex;
public int parentIndex;
public int elementTypeIndex; // we can probably remove this one. Only used for enums
public int genericContainerIndex;
public uint flags;
public int fieldStart;
public int methodStart;
public int eventStart;
public int propertyStart;
public int nestedTypesStart;
public int interfacesStart;
public int vtableStart;
public int interfaceOffsetsStart;
public ushort method_count;
public ushort property_count;
public ushort field_count;
public ushort event_count;
public ushort nested_type_count;
public ushort vtable_count;
public ushort interfaces_count;
public ushort interface_offsets_count;
// bitfield to portably encode boolean values as single bits
// 01 - valuetype;
// 02 - enumtype;
// 03 - has_finalize;
// 04 - has_cctor;
// 05 - is_blittable;
// 06 - is_import_or_windows_runtime;
// 07-10 - One of nine possible PackingSize values (0, 1, 2, 4, 8, 16, 32, 64, or 128)
// 11 - PackingSize is default
// 12 - ClassSize is default
// 13-16 - One of nine possible PackingSize values (0, 1, 2, 4, 8, 16, 32, 64, or 128) - the specified packing size (even for explicit layouts)
public uint bitfield;
public uint token;
public bool IsValueType => (bitfield & 0x1) == 1;
public bool IsEnum => ((bitfield >> 1) & 0x1) == 1;
}
public class AssemblyString
{
public byte[]? name;
public byte[]? culture;
public byte[]? public_key;
}
public class TypeString
{
public byte[]? name;
public byte[]? namespaze;
}
public class Tmp
{
public Tmp(Type type,object Header)
{
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo field in fields)
{
Console.WriteLine("Tyoe:" + field.FieldType + " Name:" + field.Name + " Value:" + field.GetValue(Header));
}
}
}
public class Metadata : BinaryStream
{
public object header;
public IL2CPP_Version InVersion;
public int version;
public int stringOffset;
public int stringCount;
public int stringLiteralOffset;
public int stringLiteralCount;
public int stringLiteralDataOffset;
public int stringLiteralDataCount;
public int imagesOffset;
public int imagesCount;
public int assembliesOffset;
public int assembliesCount;
public int windowsRuntimeTypeNamesOffset;
public int windowsRuntimeTypeNamesSize;
public int typeDefinitionsOffset;
public int typeDefinitionsCount;
public StringLiteral[] stringLiterals;
public ImageDefinition[] imageDefinitions;
public Il2CppAssemblyDefinition[] assemblyDefs;
public Il2CppWindowsRuntimeTypeNamePair[] il2CppWindowsRuntimeTypeNamePairs;
public Il2CppTypeDefinition[] il2CppTypeDefinitions;
Stream metadatastream;
public Metadata(Stream i_metadatastream,Type HeaderType,object Header, IL2CPP_Version Version) : base(i_metadatastream)
{
InVersion = Version;
metadatastream = i_metadatastream;
header = Header;
version = (int)HeaderType.GetField("version").GetValue(Header);
stringOffset = (int)HeaderType.GetField("stringOffset").GetValue(Header);
stringLiteralOffset = (int)HeaderType.GetField("stringLiteralOffset").GetValue(Header);
imagesOffset = (int)HeaderType.GetField("imagesOffset").GetValue(Header);
stringLiteralDataOffset = (int)HeaderType.GetField("stringLiteralDataOffset").GetValue(Header);
assembliesOffset = (int)HeaderType.GetField("assembliesOffset").GetValue(Header);
windowsRuntimeTypeNamesOffset = (int)HeaderType.GetField("windowsRuntimeTypeNamesOffset").GetValue(Header);
typeDefinitionsOffset = (int)HeaderType.GetField("typeDefinitionsOffset").GetValue(Header);
if (Version == IL2CPP_Version.V24_4)
{
stringCount = (int)HeaderType.GetField("stringCount").GetValue(Header);
stringLiteralCount = (int)HeaderType.GetField("stringLiteralCount").GetValue(Header);
imagesCount = (int)HeaderType.GetField("imagesCount").GetValue(Header);
stringLiteralDataCount = (int)HeaderType.GetField("stringLiteralDataCount").GetValue(Header);
assembliesCount = (int)HeaderType.GetField("assembliesCount").GetValue(Header);
windowsRuntimeTypeNamesSize = (int)HeaderType.GetField("windowsRuntimeTypeNamesSize").GetValue(Header);
typeDefinitionsCount = (int)HeaderType.GetField("typeDefinitionsCount").GetValue(Header);
}
else if(Version == IL2CPP_Version.V28)
{
stringCount = (int)HeaderType.GetField("stringSize").GetValue(Header);
stringLiteralCount = (int)HeaderType.GetField("stringLiteralSize").GetValue(Header);
imagesCount = (int)HeaderType.GetField("imagesSize").GetValue(Header);
stringLiteralDataCount = (int)HeaderType.GetField("stringLiteralDataSize").GetValue(Header);
assembliesCount = (int)HeaderType.GetField("assembliesSize").GetValue(Header);
windowsRuntimeTypeNamesSize = (int)HeaderType.GetField("windowsRuntimeTypeNamesSize").GetValue(Header);
typeDefinitionsCount = (int)HeaderType.GetField("typeDefinitionsSize").GetValue(Header);
}
stringLiterals = GetLiterals();
imageDefinitions = GetImageDefinitions();
assemblyDefs = GetIl2CppAssemblyDefinitions();
il2CppWindowsRuntimeTypeNamePairs = GetCppWindowsRuntimeTypeNamePairs();
il2CppTypeDefinitions = GetIl2CppTypeDefinitions();
}
StringLiteral[] GetLiterals()
{
List<StringLiteral> stringLiterals = new List<StringLiteral>();
BinaryReader reader = new BinaryReader(metadatastream);
reader.BaseStream.Position = stringLiteralOffset;
for (int i = 0; i < stringLiteralCount / SizeOf(typeof(StringLiteral)); i++) // 8 = sizeof(Il2CppStringLiteral)
{
stringLiterals.Add(new StringLiteral
{
Length = reader.ReadUInt32(),
Offset = reader.ReadUInt32()
});
}
return stringLiterals.ToArray();
}
ImageDefinition[] GetImageDefinitions()
{
List<ImageDefinition> ImageDefinitions = new List<ImageDefinition>();
BinaryReader reader = new BinaryReader(metadatastream);
reader.BaseStream.Position = imagesOffset;
for (int i = 0; i < imagesCount / SizeOf(typeof(ImageDefinition)); i++) // 40 = sizeof(ImageDefinition)
{
ImageDefinitions.Add(new ImageDefinition
{
nameIndex = reader.ReadUInt32(),
assemblyIndex = reader.ReadInt32(),
typeStart = reader.ReadInt32(),
typeCount = reader.ReadUInt32(),
exportedTypeStart = reader.ReadInt32(),
exportedTypeCount = reader.ReadUInt32(),
entryPointIndex = reader.ReadInt32(),
token = reader.ReadUInt32(),
customAttributeStart = reader.ReadInt32(),
customAttributeCount = reader.ReadUInt32(),
});
}
return ImageDefinitions.ToArray();
}
Il2CppAssemblyDefinition[] GetIl2CppAssemblyDefinitions()
{
return ReadMetadataClassArray<Il2CppAssemblyDefinition>((uint)assembliesOffset, assembliesCount);
}
Il2CppWindowsRuntimeTypeNamePair[] GetCppWindowsRuntimeTypeNamePairs()
{
return ReadMetadataClassArray<Il2CppWindowsRuntimeTypeNamePair>((uint)windowsRuntimeTypeNamesOffset, windowsRuntimeTypeNamesSize);
}
Il2CppTypeDefinition[] GetIl2CppTypeDefinitions()
{
return ReadMetadataClassArray<Il2CppTypeDefinition>((uint)typeDefinitionsOffset, typeDefinitionsCount);
}
public List<byte[]> GetBytesFromStringLiteral(StringLiteral[] stringLiterals)
{
List<byte[]> strBytes = new List<byte[]>();
BinaryReader reader = new BinaryReader(metadatastream);
for (int i = 0; i < stringLiterals.Length; i++)
{
reader.BaseStream.Position = stringLiteralDataOffset + stringLiterals[i].Offset;
strBytes.Add(reader.ReadBytes((int)stringLiterals[i].Length));
}
return strBytes;
}
public Stream SetCryptedStreamToMetadata(List<byte[]> CryptedStringLiteralBytes, byte[] allString,IL2CPP_Version ver)
{
Stream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
metadatastream.Position = 0;
metadatastream.CopyTo(writer.BaseStream);
writer.BaseStream.Position = 0;
CryptHeader cryptHeader = new CryptHeader(header, ver, metadatastream.Length);
writer.Write(cryptHeader.frontHeader.sign); // 24
writer.Write(cryptHeader.frontHeader.offset); // 8
writer.Write(cryptHeader.frontHeader.length); // 4
writer.Write(cryptHeader.frontHeader.key); // 32
#if NET6_0_OR_GREATER
writer.Write(RandomNumberGenerator.GetBytes(cryptHeader.frontHeader.OriginLegnth - 68));
#elif NET481
byte[] temp = new byte[cryptHeader.frontHeader.OriginLegnth - 68];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(temp);
writer.Write(temp);
#endif
for (int i = 0; i < stringLiterals.Length; i++) //加密StringLiteral
{
writer.BaseStream.Position = stringLiteralDataOffset + stringLiterals[i].Offset;
writer.Write(CryptedStringLiteralBytes[i]);
}
writer.BaseStream.Position = stringOffset;
writer.Write(allString); //加密String
writer.BaseStream.Position = stringLiteralOffset;
for (int i = 0; i < stringLiterals.Length; i++) // 倒置StringLiteral
{
writer.Write(stringLiterals[i].Offset);
writer.Write(stringLiterals[i].Length);
}
writer.BaseStream.Position = writer.BaseStream.Length;
writer.Write(cryptHeader.Crypted_Header);
stream.Position = 0;
return stream;
}
public List<byte[]> GetImageStringsFromImageDefinitions(ImageDefinition[] imageDefinitions)
{
List<byte[]> strings = new List<byte[]>();
BinaryReader reader = new BinaryReader(metadatastream);
for (int i = 0; i < imageDefinitions.Length; i++)
{
strings.Add(GetStringFromIndex(imageDefinitions[i].nameIndex));
}
return strings;
}
public List<AssemblyString> GetAssemblyStringsFromIl2CppAssemblyDefinition(Il2CppAssemblyDefinition[] il2CppAssemblyDefinitions)
{
List<byte[]> strings = new List<byte[]>();
List<AssemblyString> assemblyStrings = new List<AssemblyString>();
BinaryReader reader = new BinaryReader(metadatastream);
for (int i = 0; i < il2CppAssemblyDefinitions.Length; i++)
{
assemblyStrings.Add(new AssemblyString
{
name = GetStringFromIndex((ulong)il2CppAssemblyDefinitions[i].aname.nameIndex),
culture = GetStringFromIndex((ulong)il2CppAssemblyDefinitions[i].aname.cultureIndex),
public_key = GetStringFromIndex((ulong)il2CppAssemblyDefinitions[i].aname.publicKeyIndex)
});
}
return assemblyStrings;
}
public List<TypeString> GetTypeStringFromIl2CppTypeDefinition(Il2CppTypeDefinition[] il2CppTypeDefinitions)
{
List<TypeString> strings = new List<TypeString>();
BinaryReader reader = new BinaryReader(metadatastream);
for (int i = 0; i < il2CppTypeDefinitions.Length; i++)
{
strings.Add(new TypeString
{
name = GetStringFromIndex((ulong)il2CppTypeDefinitions[i].nameIndex),
namespaze = GetStringFromIndex((ulong)il2CppTypeDefinitions[i].namespaceIndex)
});
}
return strings;
}
public byte[] GetStringFromIndex(ulong index)
{
return (ReadStringToNull(((uint)stringOffset) + index));
}
byte[] ReadStringToNull(ulong addr)
{
BinaryReader reader = new BinaryReader(metadatastream);
reader.BaseStream.Position = (long)addr;
var bytes = new List<byte>();
byte b;
while ((b = reader.ReadByte()) != 0)
bytes.Add(b);
return bytes.ToArray();
}
public int SizeOf(Type type)
{
var size = 0;
foreach (var i in type.GetFields())
{
var attr = (VersionAttribute)Attribute.GetCustomAttribute(i, typeof(VersionAttribute));
if (attr != null)
{
if (version < attr.Min || version > attr.Max)
continue;
}
var fieldType = i.FieldType;
if (fieldType.IsPrimitive)
{
size += GetPrimitiveTypeSize(fieldType.Name);
}
else if (fieldType.IsEnum)
{
var e = fieldType.GetField("value__").FieldType;
size += GetPrimitiveTypeSize(e.Name);
}
else if (fieldType.IsArray)
{
var arrayLengthAttribute = i.GetCustomAttribute<ArrayLengthAttribute>();
size += arrayLengthAttribute.Length;
}
else
{
size += SizeOf(fieldType);
}
}
return size;
int GetPrimitiveTypeSize(string name)
{
switch (name)
{
case "Int32":
case "UInt32":
return 4;
case "Int16":
case "UInt16":
return 2;
default:
return 0;
}
}
}
private T[] ReadMetadataClassArray<T>(uint addr, int count) where T : new()
{
return ReadClassArray<T>(addr, count / SizeOf(typeof(T)));
}
public byte[] GetAllStringFromMeta()
{
BinaryReader reader = new BinaryReader(metadatastream);
reader.BaseStream.Position = stringOffset;
List<byte> bytes = new List<byte>();
for (int i = 0; i < stringCount; i++)
{
bytes.Add(reader.ReadByte());
}
return bytes.ToArray();
}
}
public class MetadataCheck : BinaryStream
{
public Il2CppGlobalMetadataHeader header;
public Il2CppImageDefinition[] imageDefs;
public Il2CppAssemblyDef[] assemblyDefs;
public MetadataCheck(Stream stream) : base(stream)
{
var sanity = ReadUInt32();
if (sanity != 0xFAB11BAF)
{
throw new InvalidDataException("ERROR: Metadata file supplied is not valid metadata file.");
}
var version = ReadInt32();
if (version < 0 || version > 1000)
{
throw new InvalidDataException("ERROR: Metadata file supplied is not valid metadata file.");
}
if (version < 16 || version > 29)
{
throw new NotSupportedException($"ERROR: Metadata file supplied is not a supported version[{version}].");
}
Version = version;
header = ReadClass<Il2CppGlobalMetadataHeader>(0);
if (version == 24)
{
if (header.stringLiteralOffset == 264)
{
Version = 24.2;
header = ReadClass<Il2CppGlobalMetadataHeader>(0);
}
else
{
imageDefs = ReadMetadataClassArray<Il2CppImageDefinition>(header.imagesOffset, header.imagesSize);
if (imageDefs.Any(x => x.token != 1))
{
Version = 24.1;
}
}
}
imageDefs = ReadMetadataClassArray<Il2CppImageDefinition>(header.imagesOffset, header.imagesSize);
if (Version == 24.2 && header.assembliesSize / 68 < imageDefs.Length)
{
Version = 24.4;
}
var v241Plus = false;
if (Version == 24.1 && header.assembliesSize / 64 == imageDefs.Length)
{
v241Plus = true;
}
if (v241Plus)
{
Version = 24.4;
}
assemblyDefs = ReadMetadataClassArray<Il2CppAssemblyDef>(header.assembliesOffset, header.assembliesSize);
if (v241Plus)
{
Version = 24.1;
}
}
private T[] ReadMetadataClassArray<T>(uint addr, int count) where T : new()
{
return ReadClassArray<T>(addr, count / SizeOf(typeof(T)));
}
private int SizeOf(Type type)
{
var size = 0;
foreach (var i in type.GetFields())
{
var attr = (VersionAttribute)Attribute.GetCustomAttribute(i, typeof(VersionAttribute));
if (attr != null)
{
if (Version < attr.Min || Version > attr.Max)
continue;
}
var fieldType = i.FieldType;
if (fieldType.IsPrimitive)
{
size += GetPrimitiveTypeSize(fieldType.Name);
}
else if (fieldType.IsEnum)
{
var e = fieldType.GetField("value__").FieldType;
size += GetPrimitiveTypeSize(e.Name);
}
else if (fieldType.IsArray)
{
var arrayLengthAttribute = i.GetCustomAttribute<ArrayLengthAttribute>();
size += arrayLengthAttribute.Length;
}
else
{
size += SizeOf(fieldType);
}
}
return size;
int GetPrimitiveTypeSize(string name)
{
switch (name)
{
case "Int32":
case "UInt32":
return 4;
case "Int16":
case "UInt16":
return 2;
default:
return 0;
}
}
}
}
public class BinaryStream : IDisposable
{
public double Version;
public bool Is32Bit;
public ulong ImageBase;
private Stream stream;
private BinaryReader reader;
private BinaryWriter writer;
private MethodInfo readClass;
private MethodInfo readClassArray;
private Dictionary<Type, MethodInfo> genericMethodCache = new Dictionary<Type, MethodInfo>();
private Dictionary<FieldInfo, VersionAttribute[]> attributeCache = new Dictionary<FieldInfo, VersionAttribute[]>();
public BinaryStream(Stream input)
{
stream = input;
reader = new BinaryReader(stream, Encoding.UTF8, true);
writer = new BinaryWriter(stream, Encoding.UTF8, true);
readClass = GetType().GetMethod("ReadClass", Type.EmptyTypes);
readClassArray = GetType().GetMethod("ReadClassArray", new[] { typeof(long) });
}
public bool ReadBoolean() => reader.ReadBoolean();
public byte ReadByte() => reader.ReadByte();
public byte[] ReadBytes(int count) => reader.ReadBytes(count);
public sbyte ReadSByte() => reader.ReadSByte();
public short ReadInt16() => reader.ReadInt16();
public ushort ReadUInt16() => reader.ReadUInt16();
public int ReadInt32() => reader.ReadInt32();
public uint ReadUInt32() => reader.ReadUInt32();
public long ReadInt64() => reader.ReadInt64();
public ulong ReadUInt64() => reader.ReadUInt64();
public float ReadSingle() => reader.ReadSingle();
public double ReadDouble() => reader.ReadDouble();
public uint ReadCompressedUInt32() => reader.ReadCompressedUInt32();
public int ReadCompressedInt32() => reader.ReadCompressedInt32();
public uint ReadULeb128() => reader.ReadULeb128();
public void Write(bool value) => writer.Write(value);
public void Write(byte value) => writer.Write(value);
public void Write(sbyte value) => writer.Write(value);
public void Write(short value) => writer.Write(value);
public void Write(ushort value) => writer.Write(value);
public void Write(int value) => writer.Write(value);
public void Write(uint value) => writer.Write(value);
public void Write(long value) => writer.Write(value);
public void Write(ulong value) => writer.Write(value);
public void Write(float value) => writer.Write(value);
public void Write(double value) => writer.Write(value);
public ulong Position
{
get => (ulong)stream.Position;
set => stream.Position = (long)value;
}
public ulong Length => (ulong)stream.Length;
private object ReadPrimitive(Type type)
{
var typename = type.Name;
switch (typename)
{
case "Int32":
return ReadInt32();
case "UInt32":
return ReadUInt32();
case "Int16":
return ReadInt16();
case "UInt16":
return ReadUInt16();
case "Byte":
return ReadByte();
case "Int64" when Is32Bit:
return (long)ReadInt32();
case "Int64":
return ReadInt64();
case "UInt64" when Is32Bit:
return (ulong)ReadUInt32();
case "UInt64":
return ReadUInt64();
default:
throw new NotSupportedException();
}
}
public T ReadClass<T>(ulong addr) where T : new()
{
Position = addr;
return ReadClass<T>();
}
public T ReadClass<T>() where T : new()
{
var type = typeof(T);
if (type.IsPrimitive)
{
return (T)ReadPrimitive(type);
}
else
{
var t = new T();
foreach (var i in t.GetType().GetFields())
{
if (!attributeCache.TryGetValue(i, out var versionAttributes))
{
if (Attribute.IsDefined(i, typeof(VersionAttribute)))
{
versionAttributes = i.GetCustomAttributes<VersionAttribute>().ToArray();
attributeCache.Add(i, versionAttributes);
}
}
if (versionAttributes?.Length > 0)
{
var read = false;
foreach (var versionAttribute in versionAttributes)
{
if (Version >= versionAttribute.Min && Version <= versionAttribute.Max)
{
read = true;
break;
}
}
if (!read)
{
continue;
}
}
var fieldType = i.FieldType;
if (fieldType.IsPrimitive)
{
i.SetValue(t, ReadPrimitive(fieldType));
}
else if (fieldType.IsEnum)
{
var e = fieldType.GetField("value__").FieldType;
i.SetValue(t, ReadPrimitive(e));
}
else if (fieldType.IsArray)
{
var arrayLengthAttribute = i.GetCustomAttribute<ArrayLengthAttribute>();
if (!genericMethodCache.TryGetValue(fieldType, out var methodInfo))
{
methodInfo = readClassArray.MakeGenericMethod(fieldType.GetElementType());
genericMethodCache.Add(fieldType, methodInfo);
}
i.SetValue(t, methodInfo.Invoke(this, new object[] { arrayLengthAttribute.Length }));
}
else
{
if (!genericMethodCache.TryGetValue(fieldType, out var methodInfo))
{
methodInfo = readClass.MakeGenericMethod(fieldType);
genericMethodCache.Add(fieldType, methodInfo);
}
i.SetValue(t, methodInfo.Invoke(this, null));
}
}
return t;
}
}
public T[] ReadClassArray<T>(long count) where T : new()
{
var t = new T[count];
for (var i = 0; i < count; i++)
{
t[i] = ReadClass<T>();
}
return t;
}
public T[] ReadClassArray<T>(ulong addr, long count) where T : new()
{
Position = addr;
return ReadClassArray<T>(count);
}
public string ReadStringToNull(ulong addr)
{
Position = addr;
var bytes = new List<byte>();
byte b;
while ((b = ReadByte()) != 0)
bytes.Add(b);
return Encoding.UTF8.GetString(bytes.ToArray());
}
public long ReadIntPtr()
{
return Is32Bit ? ReadInt32() : ReadInt64();
}
public ulong ReadUIntPtr()
{
return Is32Bit ? ReadUInt32() : ReadUInt64();
}
public ulong PointerSize
{
get => Is32Bit ? 4ul : 8ul;
}
public BinaryReader Reader => reader;
public BinaryWriter Writer => writer;
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
reader.Close();
writer.Close();
stream.Close();
}
}
public void Dispose()
{
Dispose(true);
}
}
public static class BinaryReaderExtensions
{
public static string ReadString(this BinaryReader reader, int numChars)
{
var start = reader.BaseStream.Position;
// UTF8 takes up to 4 bytes per character
var str = Encoding.UTF8.GetString(reader.ReadBytes(numChars * 4)).Substring(0, numChars);
// make our position what it would have been if we'd known the exact number of bytes needed.
reader.BaseStream.Position = start;
reader.ReadBytes(Encoding.UTF8.GetByteCount(str));
return str;
}
public static uint ReadULeb128(this BinaryReader reader)
{
uint value = reader.ReadByte();
if (value >= 0x80)
{
var bitshift = 0;
value &= 0x7f;
while (true)
{
var b = reader.ReadByte();
bitshift += 7;
value |= (uint)((b & 0x7f) << bitshift);
if (b < 0x80)
break;
}
}
return value;
}
public static uint ReadCompressedUInt32(this BinaryReader reader)
{
uint val;
var read = reader.ReadByte();
if ((read & 0x80) == 0)
{
// 1 byte written
val = read;
}
else if ((read & 0xC0) == 0x80)
{
// 2 bytes written
val = (read & ~0x80u) << 8;
val |= reader.ReadByte();
}
else if ((read & 0xE0) == 0xC0)
{
// 4 bytes written
val = (read & ~0xC0u) << 24;
val |= ((uint)reader.ReadByte() << 16);
val |= ((uint)reader.ReadByte() << 8);
val |= reader.ReadByte();
}
else if (read == 0xF0)
{
// 5 bytes written, we had a really large int32!
val = reader.ReadUInt32();
}
else if (read == 0xFE)
{
// Special encoding for Int32.MaxValue
val = uint.MaxValue - 1;
}
else if (read == 0xFF)
{
// Yes we treat UInt32.MaxValue (and Int32.MinValue, see ReadCompressedInt32) specially
val = uint.MaxValue;
}
else
{
throw new Exception("Invalid compressed integer format");
}
return val;
}
public static int ReadCompressedInt32(this BinaryReader reader)
{
var encoded = reader.ReadCompressedUInt32();
// -UINT32_MAX can't be represted safely in an int32_t, so we treat it specially
if (encoded == uint.MaxValue)
return int.MinValue;
bool isNegative = (encoded & 1) != 0;
encoded >>= 1;
if (isNegative)
return -(int)(encoded + 1);
return (int)encoded;
}
}
}