-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathUniResolver.h
More file actions
1697 lines (1510 loc) · 57.9 KB
/
Copy pathUniResolver.h
File metadata and controls
1697 lines (1510 loc) · 57.9 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
//**************************************//
// Hi UniResolver //
// Author: AlembicOrg //
// Version: v3.1.3 //
// Branch: il2cpp //
// License: GPL-3.0 license //
//**************************************//
// Change Log (Started since v1.8):
// Release v3.1.3:
// 1. Add KrOr.h (compile-time encrypted string / scoped decryption utilities) and wire it into the codebase.
// 2. Replace raw string-literal templates with EncryptedText/KrOr NTTPs and KROR/ENCRYPTED_STRING usage in NaResolver templates and macros.
// 3. Add Method::GetToken and NaResolver::GetMethod(Class,int) to support token-based method lookup; update MemberMethodInfo and METHOD_INFO to use tokens.
// 4. Update example project and main.cpp to include KrOr.h and use the new encrypted/token APIs. Also update .gitignore to ignore /v4.
// Release v3.1.2:
// 1. Normalized the macro METHOD to METHOD_INFO because in essence it actually defines a static method info store
// Release v3.1.1:
// 1. Change the macro CLASS in order to preserve some special assembly names from vs formatting, just like Assembly-CSharp
// Release v3.1:
// 1. Add test engine for finding out the wrong data at setup time
// 2. Change the field backing field name handle logic
// 3. Fixup some bug of unusable format variables
// Release v3.0.1:
// 1. Normalized the code
// 2. Add new features about field and methods
// Release v3.0:
// 1. Normalized the code
// 2. Changed the original mostly macro structure
// Release v2.2:
// 1. Re-separate the runtime-specific versions
// Release v2.1.5:
// 1. Fixup the bug of being unable to get nested class
// 2. Add more new api about getting class, especially nested classes
// Release v2.1.4:
// 1. Fixup some visible bus
// 2. Change the logic of setting and getting the fields
// Release v2.1.3:
// 1. Remove the exception
// 2. Fixup some visible bus
// Release v2.1.2:
// 1. Add runtime invoke method
// Release v2.1.1:
// 1. Add some macros about the static fields
// Release v2.1:
// 1. Rename some unreasonable variables
// 2. Add api about the fields
// Release v2.0:
// 1. Remake most of codes
// 2. Unified the runtime-specific implementations
// 3. Remove that enforce cpp version requirements
// 4. Remove the structure of signature
// Release v1.8:
// 1. Add pre-register mechanism, all class, method and field must register
// 2. Add a exception class
//
#undef GetClassName
#pragma once
#ifndef H_NARESOLVER
#define H_NARESOLVER
#include <Windows.h>
#include <array>
#include <atomic>
#include <concepts>
#include <cstdint>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include <unordered_map>
#include "KrOr.h"
#include "VmApi.h"
#undef GetObject
#undef RegisterClass
#undef TEXT
#ifndef _HAS_CXX20
#error "This library requires C++20 standard"
#endif
#define TEXT(str) KROR((str)).CStr()
class UniResolverContext
{
public:
class Class
{
public:
std::string assemblyName = std::string();
std::string namespaceName = std::string();
std::string className = std::string();
VmGeneralType::Class klass = nullptr;
VmGeneralType::Type type = nullptr;
std::unordered_map<std::string, Class> nestedClasses = {};
Class() {}
Class(const Class& klass)
: assemblyName(klass.assemblyName), namespaceName(klass.namespaceName), className(klass.className), klass(klass.klass), type(klass.type), nestedClasses(klass.nestedClasses) {}
Class(const std::string& assemblyName, const std::string& namespaceName, const std::string& className, const VmGeneralType::Class& klass, const VmGeneralType::Type& type)
: assemblyName(assemblyName), namespaceName(namespaceName), className(className), klass(klass), type(type) {}
operator VmGeneralType::Class() { return klass; }
operator VmGeneralType::Type() { return type; }
operator bool() { return klass && type; }
void AddNestedClass(const std::string name, const Class& nestedClass);
Class FindNestedClass(const std::string name) const;
};
class Method
{
public:
std::string returnTypeName = std::string();
std::string methodName = std::string();
std::vector<std::string> parametersTypeName = std::vector<std::string>();
VmGeneralType::Method method = nullptr;
Method() {}
Method(const std::string& returnTypeName, const std::string& methodName, std::vector<std::string> parametersTypeName, VmGeneralType::Method method) : returnTypeName(returnTypeName), methodName(methodName), parametersTypeName(parametersTypeName), method(method) {}
operator VmGeneralType::Method() { return method; }
operator bool() { return method; }
};
class NameMap
{
public:
using Map = std::unordered_map<std::string, std::string>;
void MapAssembly(const std::string& name, const std::string& relocatedName);
void MapNamespace(const std::string& assembly, const std::string& name, const std::string& relocatedName);
void MapClass(const std::string& assembly, const std::string& nameSpace, const std::string& name, const std::string& relocatedName);
void MapNestedClass(const std::string& assembly, const std::string& nameSpace, const std::string& parentName, const std::string& name, const std::string& relocatedName);
void MapMethod(const std::string& assembly, const std::string& nameSpace, const std::string& className, const std::string& name, const std::string& relocatedName);
void MapMethod(const std::string& assembly, const std::string& nameSpace, const std::string& className, const std::string& returnTypeName, const std::string& name, const std::vector<std::string>& parametersTypeName, const std::string& relocatedName);
void MapField(const std::string& assembly, const std::string& nameSpace, const std::string& className, const std::string& name, const std::string& relocatedName);
void MapType(const std::string& name, const std::string& relocatedName);
[[nodiscard]] std::string RelocateAssembly(const std::string& name) const;
[[nodiscard]] std::string RelocateNamespace(const std::string& assembly, const std::string& name) const;
[[nodiscard]] std::string RelocateClass(const std::string& assembly, const std::string& nameSpace, const std::string& name) const;
[[nodiscard]] std::string RelocateNestedClass(const std::string& assembly, const std::string& nameSpace, const std::string& parentName, const std::string& name) const;
[[nodiscard]] std::string RelocateMethod(const std::string& assembly, const std::string& nameSpace, const std::string& className, const std::string& returnTypeName, const std::string& name, const std::vector<std::string>& parametersTypeName) const;
[[nodiscard]] std::string RelocateField(const std::string& assembly, const std::string& nameSpace, const std::string& className, const std::string& name) const;
[[nodiscard]] std::string RelocateType(const std::string& name) const;
void Clear();
[[nodiscard]] bool Empty() const noexcept;
private:
Map assemblies = {};
Map namespaces = {};
Map classes = {};
Map nestedClasses = {};
Map methods = {};
Map methodSignatures = {};
Map fields = {};
Map types = {};
template<typename... Parts>
[[nodiscard]] static std::string MakeKey(const Parts&... parts)
{
std::string key;
((key.append(parts), key.push_back('\0')), ...);
return key;
}
[[nodiscard]] static std::string MakeMethodKey(
const std::string& assembly,
const std::string& nameSpace,
const std::string& className,
const std::string& returnTypeName,
const std::string& name,
const std::vector<std::string>& parametersTypeName);
[[nodiscard]] static std::string Relocate(const Map& map, const std::string& key, const std::string& fallback);
};
class ContextCache
{
public:
using AssemblyMap = std::unordered_map<std::string, VmGeneralType::Assembly>;
using ClassPathMap = std::unordered_map<std::string, // Assembly
std::unordered_map<std::string, // Namespace
std::unordered_map<std::string, Class> // Class
>
>;
private:
AssemblyMap assemblyMap = {};
ClassPathMap classPathMap = {};
public:
ContextCache() {}
void RegisterAssembly(const std::string& name, VmGeneralType::Assembly assembly);
Class RegisterClass(const std::string& assembly, const std::string& nameSpace, const std::string& name, VmGeneralType::Class klass, VmGeneralType::Type type);
VmGeneralType::Assembly GetAssembly(const std::string& name) const;
Class GetClass(const std::string& assembly, const std::string& nameSpace, const std::string& name) const;
Class& GetClass(const std::string& assembly, const std::string& nameSpace, const std::string& name);
void Clear();
};
private:
VmGeneralType::Domain domain = nullptr;
VmGeneralType::Thread thread = nullptr;
ContextCache cache = ContextCache();
NameMap nameMap = NameMap();
bool ownsThread = false;
mutable std::recursive_mutex stateMutex;
public:
bool Setup();
void Destroy();
void SetNameMap(NameMap map);
[[nodiscard]] const NameMap& GetNameMap() const noexcept;
void ClearNameMap();
Class GetClass(const std::string& assemblyName, const std::string& namespaceName, const std::string& className);
Class GetClass(Class parent, const std::string& className);
Method GetMethod(Class parent, const std::string& returnTypeName, const std::string& methodName, const std::vector<std::string>& parametersTypeName);
Method GetMethod(Class parent, int token);
VmGeneralType::Field GetField(Class parent, const std::string& fieldName);
};
template <typename Tuple, std::size_t... I>
auto TupleToVectorImpl(const Tuple& t, std::index_sequence<I...>)
{
return std::vector<std::string>{std::string(std::get<I>(t))...};
}
template <typename... Args>
auto TupleToVector(const std::tuple<Args...>& t)
{
return TupleToVectorImpl(t, std::index_sequence_for<Args...>{});
}
namespace Template
{
namespace Detail
{
class RuntimeThreadAttachmentGuard final
{
public:
RuntimeThreadAttachmentGuard() noexcept
{
thread = VmGeneralType::api.GetCurrentThread();
if (thread != nullptr) return;
const VmGeneralType::Domain domain = VmGeneralType::api.GetDomain();
if (domain == nullptr) return;
thread = VmGeneralType::api.AttachThread(domain);
ownsAttachment = thread != nullptr;
}
~RuntimeThreadAttachmentGuard()
{
if (ownsAttachment && thread != nullptr)
VmGeneralType::api.DetachThread(thread);
}
RuntimeThreadAttachmentGuard(const RuntimeThreadAttachmentGuard&) = delete;
RuntimeThreadAttachmentGuard& operator=(
const RuntimeThreadAttachmentGuard&) = delete;
[[nodiscard]] bool IsAttached() const noexcept { return thread != nullptr; }
private:
VmGeneralType::Thread thread = nullptr;
bool ownsAttachment = false;
};
template<typename Value>
consteval void AppendTypeIdValue(std::uint64_t& state, Value value) noexcept
{
using UnsignedValue = std::make_unsigned_t<Value>;
UnsignedValue unsignedValue = static_cast<UnsignedValue>(value);
for (std::size_t byteIndex = 0U; byteIndex < sizeof(Value); ++byteIndex)
{
state ^= static_cast<std::uint64_t>(unsignedValue & static_cast<UnsignedValue>(0xFFU));
state *= 0x100000001B3ULL;
unsignedValue >>= 8U;
}
}
template<typename Encrypted>
consteval void AppendTypeIdPart(std::uint64_t& state, const Encrypted& value) noexcept
{
using CharType = typename Encrypted::ValueType;
using UnsignedCharType = std::make_unsigned_t<CharType>;
constexpr std::size_t kMaximumSize = Encrypted::kBlockCount * Encrypted::kUnitsPerBlock;
std::size_t size = 0U;
while (size < kMaximumSize && EncryptedText::Detail::ReadCodeUnit(value, size) != CharType{})
{
++size;
}
AppendTypeIdValue(state, static_cast<std::uint64_t>(size));
AppendTypeIdValue(state, static_cast<std::uint8_t>(sizeof(CharType)));
for (std::size_t index = 0U; index < size; ++index)
{
UnsignedCharType codeUnit = static_cast<UnsignedCharType>(
EncryptedText::Detail::ReadCodeUnit(value, index));
AppendTypeIdValue(state, codeUnit);
}
}
template<typename... EncryptedParts>
[[nodiscard]] consteval std::uint64_t MakeTypeId(const EncryptedParts&... parts) noexcept
{
std::uint64_t state = 0xCBF29CE484222325ULL;
(AppendTypeIdPart(state, parts), ...);
return EncryptedText::Detail::NormalizeSeed(EncryptedText::Detail::Mix(state));
}
template<typename EncryptedName>
[[nodiscard]] consteval std::uint64_t MakeNestedTypeId(
std::uint64_t declaringTypeId,
const EncryptedName& name) noexcept
{
std::uint64_t state = 0xCBF29CE484222325ULL;
AppendTypeIdValue(state, declaringTypeId);
AppendTypeIdPart(state, name);
return EncryptedText::Detail::NormalizeSeed(EncryptedText::Detail::Mix(state));
}
template<typename... ArgumentTypeIds>
[[nodiscard]] consteval std::uint64_t MakeClosedGenericTypeId(
std::uint64_t definitionTypeId,
ArgumentTypeIds... argumentTypeIds) noexcept
{
std::uint64_t state = 0xCBF29CE484222325ULL;
AppendTypeIdValue(state, definitionTypeId);
AppendTypeIdValue(state, static_cast<std::uint64_t>(sizeof...(ArgumentTypeIds)));
(AppendTypeIdValue(state, argumentTypeIds), ...);
return EncryptedText::Detail::NormalizeSeed(EncryptedText::Detail::Mix(state));
}
[[nodiscard]] consteval std::uint64_t MakeArrayTypeId(
const std::uint64_t elementTypeId,
const std::size_t rank) noexcept
{
std::uint64_t state = 0xCBF29CE484222325ULL;
constexpr std::uint64_t kArrayDomain = 0x4172726179547970ULL;
AppendTypeIdValue(state, kArrayDomain);
AppendTypeIdValue(state, elementTypeId);
AppendTypeIdValue(state, static_cast<std::uint64_t>(rank));
return EncryptedText::Detail::NormalizeSeed(EncryptedText::Detail::Mix(state));
}
template<typename T>
inline constexpr bool IsStdString = std::is_same_v<std::remove_cvref_t<T>, std::string>;
template<typename T>
using DirectArgument = std::conditional_t<IsStdString<T>, VmGeneralType::String, std::decay_t<T>>;
template<typename T>
DirectArgument<T> ConvertArgument(T&& value)
{
if constexpr (IsStdString<T>)
{
return VmGeneralType::api.NewString(value);
}
else
{
return std::forward<T>(value);
}
}
template<typename T>
void* GetRuntimeParameter(T& value) noexcept
{
if constexpr (std::is_pointer_v<T>)
{
return const_cast<void*>(reinterpret_cast<const void*>(value));
}
else
{
return std::addressof(value);
}
}
template<typename>
inline constexpr bool AlwaysFalse = false;
template<typename ClassInfo>
[[nodiscard]] consteval std::uint64_t GetClassInfoTypeId(
const ClassInfo& classInfo)
{
if constexpr (requires { classInfo.TypeId; })
return classInfo.TypeId;
else
return std::remove_cvref_t<ClassInfo>::GetTypeId();
}
}
template<typename Identity, typename = void>
struct ManagedStorageTraits
{
};
template<typename Identity>
struct ManagedStorageTraits<Identity,
std::void_t<typename Identity::ManagedStorageType>>
{
using Type = typename Identity::ManagedStorageType;
};
template<typename Type, bool IsManagedIdentity = std::is_class_v<Type>>
struct ManagedTypeTraitsBase
{
using StorageType = typename ManagedStorageTraits<Type>::Type;
static constexpr std::uint64_t TypeId =
Detail::GetClassInfoTypeId(Type::ThisClassInfo);
};
template<typename Type>
struct ManagedTypeTraitsBase<Type, false>
{
static_assert(
Detail::AlwaysFalse<Type>,
"ManagedTypeTraits expects a managed type identity declared by a UniResolver type macro");
using StorageType = void;
static constexpr std::uint64_t TypeId = 0U;
};
template<typename Type>
struct ManagedTypeTraits : ManagedTypeTraitsBase<std::remove_cvref_t<Type>>
{
};
template<typename Type>
using ManagedStorage = typename ManagedStorageTraits<
std::remove_cvref_t<Type>>::Type;
template<typename T>
concept ManagedType = std::is_class_v<std::remove_cvref_t<T>> && requires
{
{ std::remove_cvref_t<T>::ThisClassInfo.Instance() } -> std::same_as<UniResolverContext::Class>;
};
template<typename T>
struct BoxedValue final
{
void* klass = nullptr;
void* monitor = nullptr;
alignas(std::remove_cvref_t<T>) std::remove_cvref_t<T> value;
[[nodiscard]] std::remove_cvref_t<T>& Value() noexcept { return value; }
[[nodiscard]] const std::remove_cvref_t<T>& Value() const noexcept { return value; }
};
template<typename T>
using NewObjectResult = std::conditional_t<
std::is_same_v<ManagedStorage<T>, std::remove_cvref_t<T>>,
BoxedValue<std::remove_cvref_t<T>>*, std::remove_cvref_t<T>*>;
template<typename T>
requires ManagedType<T>
[[nodiscard]] NewObjectResult<T> NewObject()
{
using ObjectType = std::remove_cvref_t<T>;
Detail::RuntimeThreadAttachmentGuard attachment;
if (!attachment.IsAttached())
{
throw std::runtime_error(
"UniResolver could not attach the current thread while allocating a managed object.");
}
UniResolverContext::Class classInfo = ObjectType::ThisClassInfo.Instance();
if (!classInfo)
{
throw std::runtime_error(
"UniResolver could not resolve the managed class while allocating an object.");
}
VmGeneralType::Object object = VmGeneralType::api.NewObject(classInfo.klass);
if (object == nullptr)
{
throw std::runtime_error("UniResolver could not allocate the managed object.");
}
return reinterpret_cast<NewObjectResult<T>>(object);
}
class ManagedInvocationException final : public std::runtime_error
{
public:
explicit ManagedInvocationException(VmGeneralType::Object exception)
: std::runtime_error("A managed method invocation raised an exception.")
{
Detail::RuntimeThreadAttachmentGuard attachment;
if (!attachment.IsAttached())
throw std::runtime_error(
"UniResolver could not attach the current thread while preserving a managed exception.");
handle = std::make_shared<Handle>(VmGeneralType::api.NewGcHandle(exception));
}
[[nodiscard]] VmGeneralType::Object Exception() const noexcept
{
Detail::RuntimeThreadAttachmentGuard attachment;
return attachment.IsAttached() && handle != nullptr ?
VmGeneralType::api.GetGcHandleTarget(handle->value) : nullptr;
}
private:
struct Handle final
{
explicit Handle(const std::uint32_t value) noexcept : value(value) {}
~Handle()
{
Detail::RuntimeThreadAttachmentGuard attachment;
if (attachment.IsAttached()) VmGeneralType::api.FreeGcHandle(value);
}
std::uint32_t value = 0U;
};
std::shared_ptr<Handle> handle;
};
template<typename R, typename... Args>
class MethodInvoker
{
static_assert(!std::is_reference_v<R>, "MethodInvoker does not support reference return values");
public:
using DirectReturnType = std::conditional_t<Detail::IsStdString<R>, VmGeneralType::String, R>;
using DirectFunctionType = DirectReturnType(*)(Detail::DirectArgument<Args>...);
using DirectInstanceFunctionType = DirectReturnType(*)(VmGeneralType::Object, Detail::DirectArgument<Args>...);
using Il2CppDirectFunctionType = DirectReturnType(*)(Detail::DirectArgument<Args>..., VmGeneralType::Method);
using Il2CppDirectInstanceFunctionType = DirectReturnType(*)(VmGeneralType::Object, Detail::DirectArgument<Args>..., VmGeneralType::Method);
using Dispatcher = R(*)(const MethodInvoker&, VmGeneralType::Method,
VmGeneralType::Object, bool, Args...);
MethodInvoker() noexcept = default;
MethodInvoker(void* address) noexcept
: directAddress(address), dispatcher(&InvokeDirectDispatcher)
{
}
MethodInvoker(VmGeneralType::Method method) noexcept
: method(method), dispatcher(&InvokeRuntimeDispatcher)
{
}
R Invoke(Args... args) const
{
return Dispatch(method, nullptr, false, std::forward<Args>(args)...);
}
R InvokeInstance(VmGeneralType::Object instance, Args... args) const
{
return Dispatch(method, instance, true, std::forward<Args>(args)...);
}
template<typename Instance>
R InvokeInstance(Instance* instance, Args... args) const
{
return InvokeInstance(
reinterpret_cast<VmGeneralType::Object>(const_cast<std::remove_const_t<Instance>*>(instance)),
std::forward<Args>(args)...);
}
R InvokeVirtual(VmGeneralType::Object instance, Args... args) const
{
Detail::RuntimeThreadAttachmentGuard attachment;
if (!attachment.IsAttached())
throw std::runtime_error(
"UniResolver could not attach the current thread to the managed runtime.");
std::atomic_ref<VmGeneralType::Object>(lastException).store(nullptr, std::memory_order_release);
VmGeneralType::Method virtualMethod = VmGeneralType::api.GetVirtualMethod(instance, method);
if (virtualMethod == nullptr)
{
throw std::runtime_error(
"UniResolver could not resolve the virtual MethodInfo.");
}
return Dispatch(virtualMethod, instance, true, std::forward<Args>(args)...);
}
template<typename Instance>
R InvokeVirtual(Instance* instance, Args... args) const
{
return InvokeVirtual(
reinterpret_cast<VmGeneralType::Object>(const_cast<std::remove_const_t<Instance>*>(instance)),
std::forward<Args>(args)...);
}
R operator()(Args... args) const
{
return Invoke(std::forward<Args>(args)...);
}
[[nodiscard]] bool IsValid() const noexcept
{
return method != nullptr || directAddress != nullptr;
}
[[nodiscard]] VmGeneralType::Object GetLastException() const noexcept
{
return std::atomic_ref<VmGeneralType::Object>(lastException).load(std::memory_order_acquire);
}
private:
using ConvertedArguments = std::tuple<Detail::DirectArgument<Args>...>;
VmGeneralType::Method method = nullptr;
mutable void* directAddress = nullptr;
mutable VmGeneralType::Object lastException = nullptr;
Dispatcher dispatcher = nullptr;
R Dispatch(VmGeneralType::Method invokeMethod,
VmGeneralType::Object instance, bool instanceCall, Args... args) const
{
Detail::RuntimeThreadAttachmentGuard attachment;
constexpr bool convertsManagedStrings = Detail::IsStdString<R> ||
(Detail::IsStdString<Args> || ...);
if ((invokeMethod != nullptr || convertsManagedStrings) &&
!attachment.IsAttached())
throw std::runtime_error(
"UniResolver could not attach the current thread to the managed runtime.");
if (dispatcher == nullptr)
{
throw std::runtime_error("UniResolver has no method invocation dispatcher.");
}
return dispatcher(*this, invokeMethod, instance, instanceCall,
std::forward<Args>(args)...);
}
[[nodiscard]] void* GetDirectAddress(VmGeneralType::Method invokeMethod) const noexcept
{
if (invokeMethod != method)
{
return VmGeneralType::api.GetMethodPointer(invokeMethod);
}
std::atomic_ref<void*> addressReference(directAddress);
void* address = addressReference.load(std::memory_order_acquire);
if (address == nullptr && invokeMethod != nullptr)
{
void* resolvedAddress = VmGeneralType::api.GetMethodPointer(invokeMethod);
addressReference.compare_exchange_strong(
address,
resolvedAddress,
std::memory_order_release,
std::memory_order_acquire);
address = addressReference.load(std::memory_order_acquire);
}
return address;
}
static R DefaultResult()
{
if constexpr (std::is_void_v<R>)
{
return;
}
else
{
return R{};
}
}
template<typename RawResult>
static R ConvertDirectResult(RawResult result)
{
if constexpr (Detail::IsStdString<R>)
{
return VmGeneralType::api.StringToUtf8(result);
}
else
{
return result;
}
}
R InvokeDirect(
VmGeneralType::Method invokeMethod,
VmGeneralType::Object instance,
bool instanceCall,
ConvertedArguments& arguments) const
{
void* address = GetDirectAddress(invokeMethod);
if (address == nullptr)
{
return DefaultResult();
}
if (instanceCall)
{
if (invokeMethod != nullptr)
{
auto function = reinterpret_cast<Il2CppDirectInstanceFunctionType>(address);
if constexpr (std::is_void_v<R>)
{
std::apply([&](auto&... values) { function(instance, values..., invokeMethod); }, arguments);
return;
}
else
{
return std::apply([&](auto&... values) { return ConvertDirectResult(function(instance, values..., invokeMethod)); }, arguments);
}
}
auto function = reinterpret_cast<DirectInstanceFunctionType>(address);
if constexpr (std::is_void_v<R>)
{
std::apply([&](auto&... values) { function(instance, values...); }, arguments);
return;
}
else
{
return std::apply([&](auto&... values) { return ConvertDirectResult(function(instance, values...)); }, arguments);
}
}
if (invokeMethod != nullptr)
{
auto function = reinterpret_cast<Il2CppDirectFunctionType>(address);
if constexpr (std::is_void_v<R>)
{
std::apply([&](auto&... values) { function(values..., invokeMethod); }, arguments);
return;
}
else
{
return std::apply([&](auto&... values) { return ConvertDirectResult(function(values..., invokeMethod)); }, arguments);
}
}
auto function = reinterpret_cast<DirectFunctionType>(address);
if constexpr (std::is_void_v<R>)
{
std::apply([&](auto&... values) { function(values...); }, arguments);
return;
}
else
{
return std::apply([&](auto&... values) { return ConvertDirectResult(function(values...)); }, arguments);
}
}
static R InvokeDirectDispatcher(const MethodInvoker& self,
VmGeneralType::Method invokeMethod,
VmGeneralType::Object instance,
bool instanceCall,
Args... args)
{
ConvertedArguments convertedArguments(
Detail::ConvertArgument<Args>(std::forward<Args>(args))...);
return self.InvokeDirect(invokeMethod, instance, instanceCall,
convertedArguments);
}
static R InvokeRuntimeDispatcher(
const MethodInvoker& self,
VmGeneralType::Method invokeMethod,
VmGeneralType::Object instance,
bool instanceCall,
Args... args)
{
(void)instanceCall;
Detail::RuntimeThreadAttachmentGuard attachment;
if (!attachment.IsAttached())
throw std::runtime_error(
"UniResolver could not attach the current thread to the managed runtime.");
std::array<VmGeneralType::String, sizeof...(Args)> runtimeStrings = {};
std::size_t runtimeStringIndex = 0U;
auto getRuntimeParameter = [&]<typename Argument>(Argument& value) -> void*
{
if constexpr (Detail::IsStdString<Argument>)
{
VmGeneralType::String& runtimeString =
runtimeStrings[runtimeStringIndex++];
runtimeString = VmGeneralType::api.NewString(value);
return runtimeString;
}
else if constexpr (std::is_pointer_v<std::remove_reference_t<Argument>>)
{
return const_cast<void*>(reinterpret_cast<const void*>(value));
}
else
{
return const_cast<void*>(static_cast<const void*>(std::addressof(value)));
}
};
std::array<void*, sizeof...(Args)> runtimeParameters = {};
std::size_t parameterIndex = 0U;
((runtimeParameters[parameterIndex++] = getRuntimeParameter(args)), ...);
VmGeneralType::RuntimeInvokeResult invokeResult = VmGeneralType::api.Invoke(
invokeMethod,
instance,
sizeof...(Args) == 0U ? nullptr : runtimeParameters.data());
std::atomic_ref<VmGeneralType::Object>(self.lastException).store(
invokeResult.exception, std::memory_order_release);
if (!invokeResult.dispatched)
{
throw std::runtime_error(
"UniResolver could not dispatch MethodInfo through il2cpp_runtime_invoke.");
}
if (invokeResult.exception != nullptr)
{
throw ManagedInvocationException(invokeResult.exception);
}
if constexpr (std::is_void_v<R>)
{
return;
}
else
{
if constexpr (Detail::IsStdString<R>)
{
return VmGeneralType::api.StringToUtf8(
reinterpret_cast<VmGeneralType::String>(invokeResult.value));
}
else if constexpr (std::is_pointer_v<R>)
{
return reinterpret_cast<R>(invokeResult.value);
}
else if constexpr (std::is_trivially_copyable_v<R>)
{
if (void* value = VmGeneralType::api.Unbox(invokeResult.value);
value != nullptr)
{
return *reinterpret_cast<const R*>(value);
}
return DefaultResult();
}
else
{
return DefaultResult();
}
}
}
};
template <EncryptedText::EncryptedString Assembly, EncryptedText::EncryptedString Namespace, EncryptedText::EncryptedString Name>
class NormalClassInfo
{
public:
static constexpr auto AssemblyName = Assembly;
static constexpr auto NamespaceName = Namespace;
static constexpr auto ClassName = Name;
static constexpr auto DeclaringClassName = EncryptedText::EncryptedString("__NONE__");
static constexpr std::uint64_t TypeId = Detail::MakeTypeId(AssemblyName, NamespaceName, ClassName);
inline static UniResolverContext::Class ClassInfoCache = UniResolverContext::Class();
inline static std::mutex ClassInfoMutex;
inline static UniResolverContext::Class Instance();
};
template <typename Declaring, EncryptedText::EncryptedString Name>
class NestedClassInfo
{
public:
static constexpr auto DeclaringClass = Declaring::ThisClassInfo;
static constexpr auto AssemblyName = DeclaringClass.AssemblyName;
static constexpr auto NamespaceName = DeclaringClass.NamespaceName;
static constexpr auto DeclaringClassName = DeclaringClass.ClassName;
static constexpr auto ClassName = Name;
static constexpr std::uint64_t TypeId = Detail::MakeNestedTypeId(
Detail::GetClassInfoTypeId(DeclaringClass), ClassName);
inline static UniResolverContext::Class ClassInfoCache = UniResolverContext::Class();
inline static std::mutex ClassInfoMutex;
inline static UniResolverContext::Class Instance();
};
template<typename Definition, typename... Arguments>
class ClosedGenericClassInfo;
template<typename Definition, typename... Arguments>
class ClosedGenericClassLocator;
template<typename Derived, typename Definition, typename... Arguments>
class ClosedGenericClassInfoBase
{
static_assert(sizeof...(Arguments) > 0U, "A closed generic class requires at least one type argument");
public:
static constexpr auto DefinitionClass = Definition::ThisClassInfo;
static constexpr auto AssemblyName = DefinitionClass.AssemblyName;
static constexpr auto NamespaceName = DefinitionClass.NamespaceName;
static constexpr auto DeclaringClassName = DefinitionClass.DeclaringClassName;
static constexpr auto ClassName = DefinitionClass.ClassName;
static consteval std::uint64_t GetTypeId()
{
return Detail::MakeClosedGenericTypeId(
DefinitionClass.TypeId,
ManagedTypeTraits<Arguments>::TypeId...);
}
inline static UniResolverContext::Class ClassInfoCache = UniResolverContext::Class();
inline static std::mutex ClassInfoMutex;
inline static UniResolverContext::Class Instance()
{
Detail::RuntimeThreadAttachmentGuard attachment;
if (!attachment.IsAttached()) return UniResolverContext::Class();
std::lock_guard lock(ClassInfoMutex);
if (ClassInfoCache.klass != nullptr)
{
return ClassInfoCache;
}
VmGeneralType::Class runtimeClass = VmGeneralType::api.ResolveRuntimeClass(
ClosedGenericClassLocator<Definition, Arguments...>::Locator);
if (runtimeClass == nullptr)
{
return UniResolverContext::Class();
}
ClassInfoCache = UniResolverContext::Class(
AssemblyName.Decrypt().CStr(),
NamespaceName.Decrypt().CStr(),
ClassName.Decrypt().CStr(),
runtimeClass,
VmGeneralType::api.GetClassType(runtimeClass));
return ClassInfoCache;
}
};
template<typename Definition, typename... Arguments>
class ClosedGenericClassInfo final
: public ClosedGenericClassInfoBase<ClosedGenericClassInfo<Definition, Arguments...>,
Definition, Arguments...>
{
};
template <typename Declaring, int MethodToken>
class MemberMethodInfo
{
public:
static constexpr auto DeclaringClass = Declaring::ThisClassInfo;
static constexpr auto Token = MethodToken;
inline static std::atomic<VmGeneralType::Method> MethodCache = nullptr;
inline static std::atomic<void*> MethodAddressCache = nullptr;
inline static VmGeneralType::Method GetMethod();
inline static void* GetMethodAddress();
[[nodiscard]] inline static VmGeneralType::Method GetVirtualMethod(
VmGeneralType::Object instance) noexcept
{
Detail::RuntimeThreadAttachmentGuard attachment;
if (!attachment.IsAttached()) return nullptr;
return VmGeneralType::api.GetVirtualMethod(instance, GetMethod());
}
template<typename Instance>
[[nodiscard]] inline static VmGeneralType::Method GetVirtualMethod(Instance* instance) noexcept
{
return GetVirtualMethod(
reinterpret_cast<VmGeneralType::Object>(const_cast<std::remove_const_t<Instance>*>(instance)));
}
};
template<typename Declaring, int MethodToken, typename... Arguments>
class ClosedGenericMethodInfo;
template<typename Derived, typename Declaring, int MethodToken, typename... Arguments>
class ClosedGenericMethodInfoBase
{
static_assert(sizeof...(Arguments) > 0U, "A closed generic method requires at least one type argument");
public:
static constexpr auto DeclaringClass = Declaring::ThisClassInfo;
static constexpr auto Token = MethodToken;
inline static std::atomic<VmGeneralType::Method> MethodCache = nullptr;
inline static std::atomic<void*> MethodAddressCache = nullptr;
inline static VmGeneralType::Method GetMethod()
{
Detail::RuntimeThreadAttachmentGuard attachment;
if (!attachment.IsAttached()) return nullptr;
if (MethodCache != nullptr)
{
return MethodCache;
}
if (!DeclaringClass.Instance())
{
return nullptr;
}
return MethodCache = VmGeneralType::api.ResolveRelativePointer(Derived::Locator);
}
inline static void* GetMethodAddress()
{
Detail::RuntimeThreadAttachmentGuard attachment;
if (!attachment.IsAttached()) return nullptr;
if (MethodAddressCache != nullptr)
{
return MethodAddressCache;
}
VmGeneralType::Method method = GetMethod();
if (method == nullptr)