Repository navigation
Expand file tree
/
Copy pathBNM.cpp
More file actions
2387 lines (2010 loc) · 98.6 KB
/
Copy pathBNM.cpp
File metadata and controls
2387 lines (2010 loc) · 98.6 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
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <list>
#include <locale>
#include <atomic>
#include <array>
#include <thread>
#include <functional>
#include <algorithm>
#include <shared_mutex>
#include <dlfcn.h>
#include "BNM.hpp"
#include "BNM_data/utf8.h"
namespace BNM_Internal {
using namespace BNM;
using namespace Structures;
// Internal variables
bool bnmLoaded = false;
void *il2cppLibraryHandle{};
const char *il2cppLibraryAbsolutePath{};
BNM_PTR il2cppLibraryAbsoluteAddress{};
#pragma pack(push, 1)
// List with variables from the il2cpp virtual machine
struct {
BNM::LoadClass Object;
BNM::Method<void *> Interlocked$$CompareExchange{};
BNM::Method<BNM::MonoType *> RuntimeType$$MakeGenericType{};
BNM::Method<BNM::MonoType *> RuntimeType$$MakePointerType{};
BNM::Method<BNM::MonoType *> RuntimeType$$make_byref_type{};
BNM::Method<IL2CPP::Il2CppReflectionMethod *> RuntimeMethodInfo$$MakeGenericMethod_impl{};
Mono::monoString **String$$Empty{};
} vmData;
#pragma pack(pop)
// il2cpp methods to avoid finding them every BNM request
struct {
IL2CPP::Il2CppImage *(*il2cpp_get_corlib)(){};
IL2CPP::Il2CppClass *(*il2cpp_class_from_name)(const IL2CPP::Il2CppImage *, const char *, const char *){};
IL2CPP::Il2CppImage *(*il2cpp_assembly_get_image)(const IL2CPP::Il2CppAssembly *){};
IL2CPP::Il2CppClass *(*il2cpp_image_get_class)(const IL2CPP::Il2CppImage *, unsigned int){};
const char *(*il2cpp_method_get_param_name)(const IL2CPP::MethodInfo *, uint32_t){};
IL2CPP::Il2CppClass *(*il2cpp_class_from_il2cpp_type)(const IL2CPP::Il2CppType *){};
IL2CPP::Il2CppClass *(*il2cpp_array_class_get)(const IL2CPP::Il2CppClass *, uint32_t){};
IL2CPP::Il2CppObject *(*il2cpp_type_get_object)(const IL2CPP::Il2CppType *){};
IL2CPP::Il2CppObject *(*il2cpp_object_new)(const IL2CPP::Il2CppClass *){};
IL2CPP::Il2CppObject *(*il2cpp_value_box)(const IL2CPP::Il2CppClass *, void *){};
IL2CPP::Il2CppArray *(*il2cpp_array_new)(const IL2CPP::Il2CppClass *, IL2CPP::il2cpp_array_size_t){};
void (*il2cpp_field_static_get_value)(const IL2CPP::FieldInfo *, void *){};
void (*il2cpp_field_static_set_value)(const IL2CPP::FieldInfo *, void *){};
Mono::monoString *(*il2cpp_string_new)(const char *){};
void *(*il2cpp_resolve_icall)(const char *){};
#ifdef BNM_DEPRECATED
IL2CPP::Il2CppDomain *(*il2cpp_domain_get)(){};
IL2CPP::Il2CppThread *(*il2cpp_thread_attach)(const IL2CPP::Il2CppDomain *){};
IL2CPP::Il2CppThread *(*il2cpp_thread_current)(){};
void (*il2cpp_thread_detach)(const IL2CPP::Il2CppThread *){};
#endif
} il2cppMethods;
#ifdef BNM_ALLOW_MULTI_THREADING_SYNC
std::shared_mutex findClassesMutex{};
std::mutex addClassMutex{}, modClassMutex{};
#endif
std::list<void(*)()> onIl2CppLoaded{};
std::list<void(*)()> &GetEvents() { return onIl2CppLoaded; }
std::string_view constructorName = OBFUSCATE_BNM(".ctor");
BNM::LoadClass customListTemplateClass{};
std::map<uint32_t, BNM::LoadClass> customListsMap{};
int32_t finalizerSlot = -1;
// Methods for new classes and for normal mode
AssemblyVector *(*Assembly$$GetAllAssemblies)(){};
void Empty() {}
#if !BNM_DISABLE_NEW_CLASSES
#ifdef BNM_ALLOW_MULTI_THREADING_SYNC
std::shared_mutex classesFindAccessMutex{};
#endif
// List with all new classes that BNM need add at runtime
std::vector<NEW_CLASSES::NewClass *> *newClassesVector = nullptr;
// List with all classes that BNM need modify at runtime
std::vector<MODIFY_CLASSES::TargetClass *> *modClassesVector = nullptr;
IL2CPP::Il2CppClass *(*old_Class$$FromIl2CppType)(IL2CPP::Il2CppType *type){};
IL2CPP::Il2CppClass *Class$$FromIl2CppType(IL2CPP::Il2CppType *type);
IL2CPP::Il2CppClass *(*old_Type$$GetClassOrElementClass)(IL2CPP::Il2CppType *type){};
IL2CPP::Il2CppClass *Type$$GetClassOrElementClass(IL2CPP::Il2CppType *type);
IL2CPP::Il2CppClass *(*old_Class$$FromName)(IL2CPP::Il2CppImage *image, const char *ns, const char *name){};
IL2CPP::Il2CppClass *Class$$FromName(IL2CPP::Il2CppImage *image, const char *namespaze, const char *name);
void ModifyClasses();
void InitNewClasses();
#if UNITY_VER <= 174
// Требуются, потому что в Unity 2017 и ниже в образах (image) и сборках (assembly) они хранятся по номерам
IL2CPP::Il2CppImage *(*old_GetImageFromIndex)(IL2CPP::ImageIndex index){};
IL2CPP::Il2CppImage *new_GetImageFromIndex(IL2CPP::ImageIndex index);
IL2CPP::Il2CppAssembly *Assembly$$Load(const char *name);
#endif
#endif
void (*orig_Image$$GetTypes)(const IL2CPP::Il2CppImage *image, bool exportedOnly, ClassVector *target){};
void Image$$GetTypes(const IL2CPP::Il2CppImage *image, bool exportedOnly, ClassVector *target);
void (*Class$$Init)(IL2CPP::Il2CppClass *klass){};
void (*old_BNM_il2cpp_init)(const char *){};
void BNM_il2cpp_init(const char *domain_name);
void SetupBNM();
#ifndef BNM_DISABLE_AUTO_LOAD
__attribute__((constructor)) void PrepareBNM();
#endif
bool InitLibraryHandle(void *handle, const char *path = nullptr, bool external = false);
// Methods for converting C# strings (monoString)
typedef std::basic_string<IL2CPP::Il2CppChar> string16;
std::string Utf16ToUtf8(IL2CPP::Il2CppChar *utf16String, size_t length) {
std::string utf8String;
utf8String.reserve(length);
utf8::unchecked::utf16to8(utf16String, utf16String + length, std::back_inserter(utf8String));
return utf8String;
}
string16 Utf8ToUtf16(const char *utf8String, size_t length) {
string16 utf16String;
if (utf8::is_valid(utf8String, utf8String + length)) {
utf16String.reserve(length);
utf8::unchecked::utf8to16(utf8String, utf8String + length, std::back_inserter(utf16String));
}
return utf16String;
}
IL2CPP::Il2CppClass *TryGetClassInImage(const IL2CPP::Il2CppImage *image, const std::string_view &namespaze, const std::string_view &name);
LoadClass TryMakeGenericClass(LoadClass genericType, const std::vector<RuntimeTypeGetter> &templateTypes) {
using namespace BNM::Operators;
if (!vmData.RuntimeType$$MakeGenericType) return {};
auto monoType = genericType.GetMonoType();
auto monoGenericsList = Mono::monoArray<MonoType *>::Create(templateTypes.size());
for (size_t i = 0; i < templateTypes.size(); ++i) (*monoGenericsList)[i] = templateTypes[i].ToLC().GetMonoType();
LoadClass typedGenericType = vmData.RuntimeType$$MakeGenericType(monoType, monoGenericsList);
monoGenericsList->Destroy();
return typedGenericType;
}
MethodBase TryMakeGenericMethod(const MethodBase &genericMethod, const std::vector<RuntimeTypeGetter> &templateTypes) {
using namespace BNM::Operators;
if (!vmData.RuntimeMethodInfo$$MakeGenericMethod_impl || !genericMethod.GetInfo()->is_generic) return {};
IL2CPP::Il2CppReflectionMethod reflectionMethod;
reflectionMethod.method = genericMethod.GetInfo();
auto monoGenericsList = Mono::monoArray<MonoType *>::Create(templateTypes.size());
for (size_t i = 0; i < templateTypes.size(); ++i) (*monoGenericsList)[i] = templateTypes[i].ToLC().GetMonoType();
MethodBase typedGenericMethod = ((&reflectionMethod)->*vmData.RuntimeMethodInfo$$MakeGenericMethod_impl)(monoGenericsList)->method;
monoGenericsList->Destroy();
return typedGenericMethod;
}
LoadClass GetPointer(LoadClass target) {
using namespace BNM::Operators;
if (!vmData.RuntimeType$$MakePointerType) return {};
return vmData.RuntimeType$$MakePointerType(target.GetMonoType());
}
LoadClass GetReference(LoadClass target) {
using namespace BNM::Operators;
if (!vmData.RuntimeType$$make_byref_type) return {};
return (target.GetMonoType()->*vmData.RuntimeType$$make_byref_type)();
}
template <class CompareMethod>
IL2CPP::MethodInfo *IterateMethods(LoadClass target, CompareMethod compare) {
auto curClass = target.klass;
do {
for (uint16_t i = 0; i < curClass->method_count; ++i) {
auto method = curClass->methods[i];
if (compare((IL2CPP::MethodInfo *)method)) return (IL2CPP::MethodInfo *) method;
}
curClass = curClass->parent;
} while (curClass);
return nullptr;
}
}
namespace BNM {
bool IsLoaded() { return BNM_Internal::bnmLoaded; }
namespace Structures::Mono {
void *CompareExchange4List(void *syncRoot) { // The only normal way to call CompareExchange for syncRoot for monoList
if (BNM_Internal::vmData.Interlocked$$CompareExchange) BNM_Internal::vmData.Interlocked$$CompareExchange((void **)&syncRoot, (void *)BNM_Internal::vmData.Object.CreateNewInstance(), (void *)nullptr);
return syncRoot;
}
std::string monoString::str() {
BNM_CHECK_SELF("ERROR: monoString dead");
if (!length) return {};
return BNM_Internal::Utf16ToUtf8(chars, length);
}
unsigned int monoString::GetHash() const {
BNM_CHECK_SELF(0);
const IL2CPP::Il2CppChar *p = chars;
unsigned int h = 0;
for (int i = 0; i < length; ++i) h = (h << 5) - h + *p; p++;
return h;
}
// Create basic C# string like il2cpp
monoString *monoString::Create(const char *str) {
const size_t length = strlen(str);
const size_t utf16Size = sizeof(IL2CPP::Il2CppChar) * length;
auto ret = (monoString *) malloc(sizeof(monoString) + utf16Size);
memset(ret, 0, sizeof(monoString) + utf16Size);
ret->length = (int)length;
auto u16 = BNM_Internal::Utf8ToUtf16(str, ret->length);
memcpy(ret->chars, u16.data(), utf16Size);
auto empty = Empty();
if (empty) ret->klass = empty->klass;
return (monoString *)ret;
}
monoString *monoString::Create(const std::string &str) { return Create(str.c_str()); }
monoString *monoString::Empty() {
if (!BNM_Internal::vmData.String$$Empty) return {};
return *BNM_Internal::vmData.String$$Empty;
}
#ifdef BNM_ALLOW_SELF_CHECKS
bool monoString::SelfCheck() volatile const {
auto *me = (monoString *)this;
if (me != nullptr) return true;
BNM_LOG_ERR("[monoString::SelfCheck] Trying to use a dead string!");
return false;
}
#endif
void monoString::Destroy() {
length = 0;
free(this);
}
}
/*** LoadClass ***/
LoadClass::LoadClass(const IL2CPP::Il2CppClass *clazz) { klass = (IL2CPP::Il2CppClass *)clazz; }
LoadClass::LoadClass(const IL2CPP::Il2CppObject *obj) {
if (!obj) return;
klass = obj->klass;
}
LoadClass::LoadClass(const IL2CPP::Il2CppType *type) {
if (!type) return;
klass = BNM_Internal::il2cppMethods.il2cpp_class_from_il2cpp_type(type);
}
LoadClass::LoadClass(const MonoType *type) {
if (!type) return;
klass = BNM_Internal::il2cppMethods.il2cpp_class_from_il2cpp_type(type->type);
}
LoadClass::LoadClass(RuntimeTypeGetter type) { klass = type; }
LoadClass::LoadClass(const std::string_view &namespaze, const std::string_view &name) {
auto assemblies = BNM_Internal::Assembly$$GetAllAssemblies();
for (auto assembly : *assemblies) {
auto image = BNM_Internal::il2cppMethods.il2cpp_assembly_get_image(assembly);
if (klass = BNM_Internal::TryGetClassInImage(image, namespaze, name); klass) return;
}
BNM_LOG_WARN("Class: [%s]::[%s] - not found.", namespaze.data(), name.data());
}
LoadClass::LoadClass(const std::string_view &namespaze, const std::string_view &name, const std::string_view &dllName) {
IL2CPP::Il2CppImage *image = nullptr;
auto assemblies = BNM_Internal::Assembly$$GetAllAssemblies();
for (auto assembly : *assemblies) {
auto currentImage = BNM_Internal::il2cppMethods.il2cpp_assembly_get_image(assembly);
if (dllName != currentImage->nameNoExt && dllName != currentImage->name) continue;
image = currentImage;
break;
}
if (!image) {
BNM_LOG_WARN("Class: [%s]::[%s]::[%s] - dll not found.", dllName.data(), namespaze.data(), name.data());
klass = nullptr;
return;
}
if (klass = BNM_Internal::TryGetClassInImage(image, namespaze, name); klass) return;
BNM_LOG_WARN("Class: [%s]::[%s]::[%s] - not found.", dllName.data(), namespaze.data(), name.data());
}
LoadClass::LoadClass(const std::string_view &namespaze, const std::string_view &name, const IL2CPP::Il2CppImage *image) {
if (klass = BNM_Internal::TryGetClassInImage(image, namespaze, name); klass) return;
BNM_LOG_WARN("Class: [%s]::[%s]::[%s] - not found.", image->name, namespaze.data(), name.data());
}
LoadClass::LoadClass(const std::string_view &namespaze, const std::string_view &name, const IL2CPP::Il2CppAssembly *assembly) {
*this = LoadClass(namespaze, name, BNM_Internal::il2cppMethods.il2cpp_assembly_get_image(assembly));
}
std::vector<LoadClass> LoadClass::GetInnerClasses(bool includeParent) const {
if (!klass) return {};
TryInit();
std::vector<LoadClass> ret{};
auto curClass = klass;
do {
for (uint16_t i = 0; i < curClass->nested_type_count; ++i) ret.emplace_back(curClass->nestedTypes[i]);
if (includeParent) curClass = curClass->parent;
else break;
} while (curClass);
return std::move(ret);
}
std::vector<FieldBase> LoadClass::GetFields(bool includeParent) const {
if (!klass) return {};
TryInit();
std::vector<FieldBase> ret{};
auto curClass = klass;
do {
auto end = curClass->fields + curClass->field_count;
for (IL2CPP::FieldInfo *currentField = curClass->fields; currentField != end; ++currentField) ret.emplace_back(currentField);
if (includeParent) curClass = curClass->parent;
else break;
} while (curClass);
return std::move(ret);
}
std::vector<MethodBase> LoadClass::GetMethods(bool includeParent) const {
if (!klass) return {};
TryInit();
std::vector<MethodBase> ret{};
auto curClass = klass;
do {
for (uint16_t i = 0; i < curClass->method_count; ++i) ret.emplace_back(curClass->methods[i]);
if (includeParent) curClass = curClass->parent;
else break;
} while (curClass);
return std::move(ret);
}
std::vector<PropertyBase> LoadClass::GetProperties(bool includeParent) const {
if (!klass) return {};
TryInit();
std::vector<PropertyBase> ret{};
auto curClass = klass;
do {
auto end = curClass->properties + curClass->property_count;
for (auto currentProperty = curClass->properties; currentProperty != end; ++currentProperty) ret.emplace_back(currentProperty);
if (includeParent) curClass = curClass->parent;
else break;
} while (curClass);
return std::move(ret);
}
MethodBase LoadClass::GetMethodByName(const std::string_view &name, int parameters) const {
if (!klass) return {};
TryInit();
auto method = BNM_Internal::IterateMethods(*this, [&name, ¶meters](IL2CPP::MethodInfo *method) {
return name == method->name && (method->parameters_count == parameters || parameters == -1);
});
if (method) return method;
BNM_LOG_WARN("Method: [%s]::[%s].[%s], %d - not found.", klass->namespaze, klass->name, name.data(), parameters);
return {};
}
MethodBase LoadClass::GetMethodByName(const std::string_view &name, const std::vector<std::string_view> ¶metersName) const {
if (!klass) return {};
TryInit();
auto parameters = (uint8_t) parametersName.size();
auto method = BNM_Internal::IterateMethods(*this, [&name, ¶meters, ¶metersName](IL2CPP::MethodInfo *method) {
if (name != method->name || method->parameters_count != parameters) return false;
for (uint8_t i = 0; i < parameters; ++i) if (BNM_Internal::il2cppMethods.il2cpp_method_get_param_name(method, i) != parametersName[i]) return false;
return true;
});
if (method) return method;
BNM_LOG_WARN("Method: [%s]::[%s].(%s), %d - not found; using parameter names.", klass->namespaze, klass->name, name.data(), parameters);
return {};
}
MethodBase LoadClass::GetMethodByName(const std::string_view &name, const std::vector<RuntimeTypeGetter> ¶metersType) const {
if (!klass) return {};
TryInit();
auto parameters = (uint8_t) parametersType.size();
auto method = BNM_Internal::IterateMethods(*this, [&name, ¶meters, ¶metersType](IL2CPP::MethodInfo *method) {
if (name != method->name || method->parameters_count != parameters) return false;
for (uint8_t i = 0; i < parameters; ++i) {
#if UNITY_VER < 212
auto param = (method->parameters + i)->parameter_type;
#else
auto param = method->parameters[i];
#endif
if (LoadClass(param).GetIl2CppClass() != parametersType[i].ToIl2CppClass()) return false;
}
return true;
});
if (method) return method;
BNM_LOG_WARN("Method: [%s]::[%s].[%s], %d - not found; using parameter types.", klass->namespaze, klass->name, name.data(), parameters);
return {};
}
PropertyBase LoadClass::GetPropertyByName(const std::string_view &name) {
if (!klass) return {};
TryInit();
auto curClass = klass;
do {
auto end = curClass->properties + curClass->property_count;
for (auto currentProperty = curClass->properties; currentProperty != end; ++currentProperty) if (name == currentProperty->name) return currentProperty;
curClass = curClass->parent;
} while (curClass);
BNM_LOG_WARN("Property: %s.(%s) - not found.", str().c_str(), name.data());
return {};
}
LoadClass LoadClass::GetInnerClass(const std::string_view &name) const {
if (!klass) return {};
TryInit();
auto curClass = klass;
do {
for (uint16_t i = 0; i < curClass->nested_type_count; ++i) {
auto cls = curClass->nestedTypes[i];
if (name == cls->name) return cls;
}
curClass = curClass->parent;
} while (curClass);
BNM_LOG_WARN("Inner class: [%s]::[%s]::[%s] - not found.", klass->namespaze, klass->name, name.data());
return {};
}
FieldBase LoadClass::GetFieldByName(const std::string_view &name) const {
if (!klass) return {};
TryInit();
auto curClass = klass;
do {
auto end = curClass->fields + curClass->field_count;
for (IL2CPP::FieldInfo *currentField = curClass->fields; currentField != end; ++currentField) {
if (name != currentField->name) continue;
return currentField;
}
curClass = curClass->parent;
} while (curClass);
BNM_LOG_WARN("Field: [%s]::[%s].(%s) - not found.", klass->namespaze, klass->name, name.data());
return {};
}
LoadClass LoadClass::GetParent() const {
if (!klass) return {};
TryInit();
return klass->parent;
}
LoadClass LoadClass::GetArray() const {
if (!klass) return {};
TryInit();
return BNM_Internal::il2cppMethods.il2cpp_array_class_get(klass, 1);
}
LoadClass LoadClass::GetPointer() const {
if (!klass) return {};
TryInit();
return BNM_Internal::GetPointer(*this);
}
LoadClass LoadClass::GetReference() const {
if (!klass) return {};
TryInit();
return BNM_Internal::GetReference(*this);
}
LoadClass LoadClass::GetGeneric(const std::vector<RuntimeTypeGetter> &templateTypes) const {
if (!klass) return {};
TryInit();
return BNM_Internal::TryMakeGenericClass(*this, templateTypes);
}
IL2CPP::Il2CppType *LoadClass::GetIl2CppType() const {
if (!klass) return nullptr;
TryInit();
#if UNITY_VER > 174
return (IL2CPP::Il2CppType *)&klass->byval_arg;
#else
return (IL2CPP::Il2CppType *)klass->byval_arg;
#endif
}
MonoType *LoadClass::GetMonoType() const {
if (!klass) return nullptr;
TryInit();
return (MonoType *) BNM_Internal::il2cppMethods.il2cpp_type_get_object(GetIl2CppType());
}
IL2CPP::Il2CppClass *LoadClass::GetIl2CppClass() const {
TryInit();
return klass;
}
BNM::RuntimeTypeGetter LoadClass::GetRuntimeType() const {
TryInit();
return {nullptr, nullptr, RuntimeTypeGetter::RuntimeModifier::None, *this};
}
LoadClass::operator BNM::RuntimeTypeGetter() const { return GetRuntimeType(); }
void *LoadClass::CreateNewInstance() const {
if (!klass) return nullptr;
TryInit();
if ((klass->flags & (0x00000080 | 0x00000020))) // TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE
BNM_LOG_WARN("You trying to create instance of abstract or interface class %s?\nIn C# this is impossible.", str().c_str());
auto obj = BNM_Internal::il2cppMethods.il2cpp_object_new(klass);
if (obj) memset((char*)obj + sizeof(IL2CPP::Il2CppObject), 0, klass->instance_size - sizeof(IL2CPP::Il2CppObject));
return (void *) obj;
}
#ifdef BNM_ALLOW_STR_METHODS
std::string LoadClass::str() const {
if (!klass) return OBFUSCATES_BNM("Dead class");
TryInit();
return OBFUSCATES_BNM("[") + klass->image->name + OBFUSCATES_BNM("]::[") + klass->namespaze + OBFUSCATES_BNM("]::[") + klass->name + OBFUSCATES_BNM("]");
}
#endif
// Try initializing class if it is alive
void LoadClass::TryInit() const { if (klass) BNM_Internal::Class$$Init(klass); }
IL2CPP::Il2CppObject *LoadClass::ObjBox(IL2CPP::Il2CppClass *klass, void *data) {
return BNM_Internal::il2cppMethods.il2cpp_value_box(klass, data);
}
IL2CPP::Il2CppArray *LoadClass::ArrayNew(IL2CPP::Il2CppClass *cls, IL2CPP::il2cpp_array_size_t length) {
return BNM_Internal::il2cppMethods.il2cpp_array_new(cls, length);
}
void *LoadClass::NewListInstance() {
return BNM_Internal::customListTemplateClass.CreateNewInstance();
}
// Method for getting and creating types for each list type
IL2CPP::Il2CppClass *Structures::Mono::__PRIVATE_MonoListData::TryGetMonoListClass(uint32_t typeHash, std::array<__PRIVATE_MonoListData::MethodData, 16> &data) {
auto &klass = BNM_Internal::customListsMap[typeHash];
if (klass) return klass;
std::map<size_t, IL2CPP::MethodInfo *> createdMethods{};
auto templateClass = BNM_Internal::customListTemplateClass.klass;
auto size = sizeof(IL2CPP::Il2CppClass) + templateClass->vtable_count * sizeof(IL2CPP::VirtualInvokeData);
auto typedClass = (IL2CPP::Il2CppClass *) malloc(size);
memcpy(typedClass, templateClass, size);
auto hash = std::hash<std::string_view>();
for (uint16_t i = 4 /* Skip System.Object's virtual methods */; i < typedClass->vtable_count; ++i) {
auto &cur = typedClass->vtable[i];
auto name = std::string_view(cur.method->name);
auto dot = name.rfind('.');
if (dot != std::string_view::npos) name = name.substr(dot + 1);
auto iterator = data.begin();
for (; iterator != data.end(); ++iterator) if (iterator->methodName == name) break;
auto &methodInfo = createdMethods[hash(name)];
if (methodInfo == nullptr) {
methodInfo = (IL2CPP::MethodInfo *) malloc(sizeof(IL2CPP::MethodInfo));
memcpy((void *) methodInfo, (void *) cur.method, sizeof(IL2CPP::MethodInfo));
methodInfo->methodPointer = (decltype(methodInfo->methodPointer)) iterator->ptr;
}
cur.method = methodInfo;
cur.methodPtr = methodInfo->methodPointer;
}
klass = typedClass;
return klass;
}
LoadClass RuntimeTypeGetter::ToLC() {
if (loadedClass) return loadedClass;
if (!name || !namespaze) return {};
loadedClass = LoadClass(namespaze, name);
if (modifier == RuntimeModifier::Array) loadedClass = loadedClass.GetArray();
else if (modifier == RuntimeModifier::Pointer) loadedClass = loadedClass.GetPointer();
else if (modifier == RuntimeModifier::Reference) loadedClass = loadedClass.GetReference();
return loadedClass;
}
LoadClass RuntimeTypeGetter::ToLC() const {
return ((RuntimeTypeGetter *)this)->ToLC();
}
RuntimeTypeGetter::operator LoadClass() { return ToLC(); }
RuntimeTypeGetter::operator LoadClass() const { return ToLC(); }
IL2CPP::Il2CppType *RuntimeTypeGetter::ToIl2CppType() { return ToLC().GetIl2CppType(); }
IL2CPP::Il2CppType *RuntimeTypeGetter::ToIl2CppType() const { return ToLC().GetIl2CppType(); }
RuntimeTypeGetter::operator IL2CPP::Il2CppType*() { return ToIl2CppType(); }
RuntimeTypeGetter::operator IL2CPP::Il2CppType*() const { return ToIl2CppType(); }
IL2CPP::Il2CppClass *RuntimeTypeGetter::ToIl2CppClass() { return ToLC().GetIl2CppClass(); }
IL2CPP::Il2CppClass *RuntimeTypeGetter::ToIl2CppClass() const { return ToLC().GetIl2CppClass(); }
RuntimeTypeGetter::operator IL2CPP::Il2CppClass*() { return ToIl2CppClass(); }
RuntimeTypeGetter::operator IL2CPP::Il2CppClass*() const { return ToIl2CppClass(); }
// For thread static fields
namespace __PRIVATE_FieldUtils {
void GetStaticValue(IL2CPP::FieldInfo *info, void *value) { return BNM_Internal::il2cppMethods.il2cpp_field_static_get_value(info, value); }
void SetStaticValue(IL2CPP::FieldInfo *info, void *value) { return BNM_Internal::il2cppMethods.il2cpp_field_static_set_value(info, value); }
}
bool CheckIsFieldStatic(IL2CPP::FieldInfo *field) {
if (!field || !field->type) return false;
return (field->type->attrs & 0x0010) != 0 && field->offset != -1 && (field->type->attrs & 0x0040) == 0;
}
FieldBase::FieldBase(IL2CPP::FieldInfo *info) {
init = info != nullptr;
if (init) {
isStatic = CheckIsFieldStatic(info);
myInfo = info;
isThreadStatic = myInfo->offset == -1;
}
}
FieldBase::FieldBase(const FieldBase &other) {
myInfo = other.myInfo;
instance = other.instance;
init = other.init;
isStatic = other.isStatic;
isThreadStatic = other.isThreadStatic;
}
FieldBase &FieldBase::SetInstance(IL2CPP::Il2CppObject *val) {
if (init && isStatic) {
BNM_LOG_WARN("Trying to set an object to the static field %s. Please remove SetInstance call in the code.", str().c_str());
return *this;
}
init = val && myInfo != nullptr;
instance = val;
return *this;
}
IL2CPP::FieldInfo *FieldBase::GetInfo() const {
if (init) return myInfo;
return {};
}
BNM_PTR FieldBase::GetOffset() const {
#ifndef BNM_ALLOW_GET_OFFSET
BNM_LOG_ERR("GetOffset is forbidden to use! Check the examples if BNM can perform the action you need. If you really need GetOffset, and BNM does not provide an API for the action you intended, then enable BNM_ALLOW_GET_OFFSET in its settings.");
return 0;
#endif
if (!init) return 0;
return myInfo->offset;
}
void *FieldBase::GetFieldPointer() const {
if (!init) return nullptr;
if (!isStatic && !CheckObj(instance)) {
BNM_LOG_ERR("Can't get a non-static %s field pointer without an object! Please set the object before trying to get the pointer.", str().c_str());
return nullptr;
} else if (isStatic && !CheckObj(myInfo->parent)) {
BNM_LOG_ERR("Something went wrong, the static field %s has no class.", str().c_str());
return nullptr;
} else if (isThreadStatic) {
BNM_LOG_ERR("Getting a pointer to thread static field is not supported, field: %s.", str().c_str());
return nullptr;
}
if (isStatic) return (void *) ((BNM_PTR) myInfo->parent->static_fields + myInfo->offset);
return (void *) ((BNM_PTR) instance + myInfo->offset);
}
MethodBase::MethodBase(const IL2CPP::MethodInfo *info) {
init = (BNM::CheckObj(info) != nullptr);
if (init) {
isStatic = (info->flags & 0x0010) == 0x0010;
isVirtual = info->slot != 65535;
myInfo = (decltype(myInfo)) info;
}
}
MethodBase::MethodBase(const MethodBase &other) {
myInfo = other.myInfo;
instance = other.instance;
init = other.init;
isStatic = other.isStatic;
isVirtual = other.isVirtual;
}
MethodBase &MethodBase::SetInstance(IL2CPP::Il2CppObject *val) {
if (!init) return *this;
if (init && isStatic) {
BNM_LOG_WARN("Trying to set an object to the static field %s. Please remove SetInstance call in the code.", str().c_str());
return *this;
}
instance = val;
return *this;
}
IL2CPP::MethodInfo *MethodBase::GetInfo() const {
if (init) return myInfo;
return {};
}
BNM_PTR MethodBase::GetOffset() const {
#ifndef BNM_ALLOW_GET_OFFSET
BNM_LOG_ERR("GetOffset is forbidden to use! Check the examples if BNM can perform the action you need. If you really need GetOffset, and BNM does not provide an API for the action you intended, then enable BNM_ALLOW_GET_OFFSET in its settings.");
return 0;
#endif
if (init) return (BNM_PTR) myInfo->methodPointer;
return {};
}
MethodBase MethodBase::GetGeneric(const std::vector<RuntimeTypeGetter> &templateTypes) const {
BNM_LOG_WARN_IF(!myInfo->is_generic, "%s method is not generic!", str().c_str());
if (!myInfo->is_generic) return {};
return BNM_Internal::TryMakeGenericMethod(*this, templateTypes);
}
MethodBase MethodBase::Virtualize() const {
if (!init || isStatic) return {};
if (!BNM::CheckObj(instance)) {
BNM_LOG_WARN("Failed to get virtual version of %s method - the object is not set", str().c_str());
return {};
}
auto klass = instance->klass;
uint16_t i = 0;
NEXT:
for (; i < klass->vtable_count; ++i) {
auto &vTable = klass->vtable[i];
auto count = vTable.method->parameters_count;
if (strcmp(vTable.method->name, myInfo->name) || count != myInfo->parameters_count) continue;
for (uint8_t p = 0; p < count; ++p) {
#if UNITY_VER < 212
auto type = (vTable.method->parameters + p)->parameter_type;
auto type2 = (myInfo->parameters + p)->parameter_type;
#else
auto type = vTable.method->parameters[p];
auto type2 = myInfo->parameters[p];
#endif
if (LoadClass(type).GetIl2CppClass() != LoadClass(type2).GetIl2CppClass()) goto NEXT;
}
return vTable.method;
}
return {};
}
PropertyBase::PropertyBase(const IL2CPP::PropertyInfo *info) {
if (!info) return;
hasGetter = hasSetter = false;
if (info->get && info->get->methodPointer) {
hasGetter = true;
getter = info->get;
}
if (info->set && info->set->methodPointer) {
hasSetter = true;
setter = info->set;
}
}
PropertyBase::PropertyBase(const PropertyBase &other) {
myInfo = other.myInfo;
getter = other.getter;
setter = other.setter;
hasGetter = other.hasGetter;
hasSetter = other.hasSetter;
}
PropertyBase::PropertyBase(const MethodBase &newGetter, const MethodBase &newSetter) {
hasGetter = hasSetter = false;
if (newGetter) {
hasGetter = true;
getter = newGetter;
}
if (newSetter) {
hasSetter = true;
setter = newSetter;
}
}
PropertyBase &PropertyBase::SetInstance(IL2CPP::Il2CppObject *val) {
if (hasGetter) getter.SetInstance(val);
if (hasSetter) setter.SetInstance(val);
return *this;
}
#ifdef BNM_DEPRECATED
bool AttachIl2Cpp() {
if (CurrentIl2CppThread()) return false;
BNM_Internal::il2cppMethods.il2cpp_thread_attach(BNM_Internal::il2cppMethods.il2cpp_domain_get());
return true;
}
IL2CPP::Il2CppThread *CurrentIl2CppThread() {
return BNM_Internal::il2cppMethods.il2cpp_thread_current();
}
void DetachIl2Cpp() {
auto thread = CurrentIl2CppThread();
if (!thread) return;
BNM_Internal::il2cppMethods.il2cpp_thread_detach(thread);
}
#endif
// Create basic C# string using il2cpp
Structures::Mono::monoString *CreateMonoString(const char *str) {
return BNM_Internal::il2cppMethods.il2cpp_string_new(str);
}
Structures::Mono::monoString *CreateMonoString(const std::string_view &str) { return CreateMonoString(str.data()); }
void *GetExternMethod(const std::string_view &str) {
auto c_str = str.data();
auto ret = BNM_Internal::il2cppMethods.il2cpp_resolve_icall(c_str);
BNM_LOG_WARN_IF(!ret, "Extern method %s not found. Please check code.", c_str);
return ret;
}
std::string_view GetIl2CppLibraryPath() {
if (!BNM_Internal::il2cppLibraryHandle) return {};
return BNM_Internal::il2cppLibraryAbsolutePath;
}
BNM_PTR GetIl2CppLibraryOffset() {
return BNM_Internal::il2cppLibraryAbsoluteAddress;
}
void *GetIl2CppLibraryHandle() {
return BNM_Internal::il2cppLibraryHandle;
}
bool InvokeHookImpl(IL2CPP::MethodInfo *m, void *newMet, void **oldMet) {
if (!m) return false;
if (oldMet) *oldMet = (void *) m->methodPointer;
m->methodPointer = (IL2CPP::Il2CppMethodPointer) newMet;
return true;
}
bool VirtualHookImpl(BNM::LoadClass targetClass, IL2CPP::MethodInfo *m, void *newMet, void **oldMet) {
if (!m || !targetClass) return false;
uint16_t i = 0;
NEXT:
for (; i < targetClass.klass->vtable_count; ++i) {
auto &vTable = targetClass.klass->vtable[i];
auto count = vTable.method->parameters_count;
if (strcmp(vTable.method->name, m->name) || count != m->parameters_count) continue;
for (uint8_t p = 0; p < count; ++p) {
#if UNITY_VER < 212
auto type = (vTable.method->parameters + p)->parameter_type;
auto type2 = (m->parameters + p)->parameter_type;
#else
auto type = vTable.method->parameters[p];
auto type2 = m->parameters[p];
#endif
if (LoadClass(type).GetIl2CppClass() != LoadClass(type2).GetIl2CppClass()) goto NEXT;
}
if (oldMet) *oldMet = (void *) vTable.methodPtr;
vTable.methodPtr = (void(*)()) newMet;
return true;
}
return false;
}
template<> bool IsA<IL2CPP::Il2CppObject *>(IL2CPP::Il2CppObject *object, IL2CPP::Il2CppClass *klass) {
if (!object || !klass) return false;
for (auto cls = object->klass; cls; cls = cls->parent) if (cls == klass) return true;
return false;
}
namespace HexUtils {
// Reverse hex string (form 001122 to 221100)
std::string ReverseHexString(const std::string &hex) {
std::string out;
for (size_t i = 0; i < hex.length(); i += 2) out.insert(0, hex.substr(i, 2));
return out;
}
// Convert hex string to value
unsigned long long HexStr2Value(const std::string &hex) { return strtoull(hex.c_str(), nullptr, 16); }
#if defined(__ARM_ARCH_7A__)
// Check is assembly is `bl ...` or `b ...`
bool IsBranchHex(const std::string &hex) {
BNM_PTR hexW = HexStr2Value(ReverseHexString(hex));
return (hexW & 0x0A000000) == 0x0A000000;
}
#elif defined(__aarch64__)
// Check is assembly is `bl ...` or `b ...`
bool IsBranchHex(const std::string &hex) {
BNM_PTR hexW = HexStr2Value(ReverseHexString(hex));
return (hexW & 0xFC000000) == 0x14000000 || (hexW & 0xFC000000) == 0x94000000;
}
#elif defined(__i386__) || defined(__x86_64__)
// Check is assembly is `call ...`
bool IsCallHex(const std::string &hex) { return hex.substr(0, 2) == OBFUSCATE_BNM("E8"); }
#elif defined(__riscv)
#error "Is it out for Android?"
#else
#error "BNM support only arm64, arm, x86 and x86_64"
#endif
const char *hexChars = OBFUSCATE_BNM("0123456789ABCDEF");
// Read memory as hex string
std::string ReadFiveBytesOfMemoryMax(BNM_PTR address, size_t len) {
char temp[5]; memset(temp, 0, len);
std::string ret;
if (memcpy(temp, (void *)address, len) == nullptr) return std::move(ret);
ret.resize(len * 2, 0);
auto buf = (char *)ret.data();
for (size_t i = 0; i < len; ++i) {
*buf++ = hexChars[temp[i] >> 4];
*buf++ = hexChars[temp[i] & 0x0F];
}
return std::move(ret);
}
// Decoding b and bl and getting address that it jumps
bool DecodeBranchOrCall(const std::string &hex, BNM_PTR offset, BNM_PTR &outOffset) {
#if defined(__ARM_ARCH_7A__) || defined(__aarch64__)
if (!IsBranchHex(hex)) return false;
#if defined(__aarch64__)
uint8_t add = 0;
#else
uint8_t add = 8;
#endif
// This line is based on capstone code
outOffset = ((int32_t)(((((HexStr2Value(ReverseHexString(hex))) & (((uint32_t)1 << 24) - 1) << 0) >> 0) << 2) << (32 - 26)) >> (32 - 26)) + offset + add;
#elif defined(__i386__) || defined(__x86_64__)
if (!IsCallHex(hex)) return false;
// Offest + address from call + size of instruction
outOffset = offset + HexStr2Value(ReverseHexString(hex).substr(0, 8)) + 5;
#else
#error "BNM support only arm64, arm, x86 and x86_64"
return false;
#endif
return true;
}
// Parsing memory and trying to find b, or bl, or call
// Than get address from it
// index: 0 - first, 1 - second and etc.
BNM_PTR FindNextJump(BNM_PTR start, int index) {
#if defined(__ARM_ARCH_7A__) || defined(__aarch64__)
BNM_PTR offset = 0;
std::string curHex = ReadFiveBytesOfMemoryMax(start, 4);
BNM_PTR outOffset = 0;