forked from focus-creative-games/il2cpp_plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRuntime.cpp
More file actions
1193 lines (994 loc) · 49.3 KB
/
Runtime.cpp
File metadata and controls
1193 lines (994 loc) · 49.3 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 "il2cpp-config.h"
#include "metadata/GenericMethod.h"
#include "os/CrashHelpers.h"
#include "os/Environment.h"
#include "os/File.h"
#include "os/Image.h"
#include "os/Initialize.h"
#include "os/LibraryLoader.h"
#include "os/Locale.h"
#include "os/MemoryMappedFile.h"
#include "os/Mutex.h"
#include "os/Path.h"
#include "os/SynchronizationContext.h"
#include "os/Thread.h"
#include "os/Socket.h"
#include "os/c-api/Allocator.h"
#include "metadata/GenericMetadata.h"
#include "vm/Array.h"
#include "vm/Assembly.h"
#include "vm/ClassLibraryPAL.h"
#include "vm/COMEntryPoints.h"
#include "vm/Class.h"
#include "vm/Domain.h"
#include "vm/Exception.h"
#include "vm/Field.h"
#include "gc/GCHandle.h"
#include "vm/Image.h"
#include "vm/LastError.h"
#include "vm/MetadataAlloc.h"
#include "vm/MetadataCache.h"
#include "vm/MetadataLock.h"
#include "vm/Method.h"
#include "vm/Reflection.h"
#include "vm/Runtime.h"
#include "vm/Thread.h"
#include "vm/Type.h"
#include "vm/StackTrace.h"
#include "vm/String.h"
#include "vm/Object.h"
#include "vm-utils/Debugger.h"
#include "vm-utils/DebugSymbolReader.h"
#include "vm/Profiler.h"
#include "utils/Logging.h"
#include <string>
#include <map>
#include "il2cpp-class-internals.h"
#include "il2cpp-object-internals.h"
#include "il2cpp-tabledefs.h"
#include "gc/GarbageCollector.h"
#include "gc/WriteBarrier.h"
#include "vm/InternalCalls.h"
#include "utils/Collections.h"
#include "utils/Memory.h"
#include "utils/StringUtils.h"
#include "utils/PathUtils.h"
#include "utils/Runtime.h"
#include "utils/Environment.h"
#include "mono/ThreadPool/threadpool-ms.h"
#include "mono/ThreadPool/threadpool-ms-io.h"
#include "icalls/mscorlib/System.Reflection/RuntimeAssembly.h"
#include "icalls/mscorlib/System.IO/MonoIO.h"
#include "vm/Monitor.h"
#include "vm-utils/Debugger.h"
#include "Baselib.h"
#include "Cpp/ReentrantLock.h"
#include "hybridclr/Runtime.h"
#include "hybridclr/Il2CppCompatibleDef.h"
Il2CppDefaults il2cpp_defaults;
bool g_il2cpp_is_fully_initialized = false;
static bool shutting_down = false;
MetadataInitializerCleanupFunc g_ClearMethodMetadataInitializedFlags = NULL;
static baselib::ReentrantLock s_InitLock;
static int32_t s_RuntimeInitCount;
typedef void (*CodegenRegistrationFunction) ();
extern CodegenRegistrationFunction g_CodegenRegistration;
namespace il2cpp
{
namespace vm
{
baselib::ReentrantLock g_MetadataLock;
static int32_t exitcode = 0;
static std::string s_ConfigDir;
static const char *s_FrameworkVersion = 0;
static const char *s_BundledMachineConfig = 0;
static Il2CppRuntimeUnhandledExceptionPolicy s_UnhandledExceptionPolicy = IL2CPP_UNHANDLED_POLICY_CURRENT;
static const void* s_UnitytlsInterface = NULL;
#define DEFAULTS_INIT(field, ns, n) do { il2cpp_defaults.field = Class::FromName (il2cpp_defaults.corlib, ns, n);\
IL2CPP_ASSERT(il2cpp_defaults.field); } while (0)
#define DEFAULTS_INIT_TYPE(field, ns, n, nativetype) do { DEFAULTS_INIT(field, ns, n); \
IL2CPP_ASSERT(il2cpp_defaults.field->instance_size == sizeof(nativetype) + (il2cpp_defaults.field->byval_arg.valuetype ? sizeof(Il2CppObject) : 0)); } while (0)
#define DEFAULTS_INIT_OPTIONAL(field, ns, n) do { il2cpp_defaults.field = Class::FromName (il2cpp_defaults.corlib, ns, n); } while (0)
#define DEFAULTS_INIT_TYPE_OPTIONAL(field, ns, n, nativetype) do { DEFAULTS_INIT_OPTIONAL(field, ns, n); \
if (il2cpp_defaults.field != NULL) \
IL2CPP_ASSERT(il2cpp_defaults.field->instance_size == sizeof(nativetype) + (il2cpp_defaults.field->byval_arg.valuetype ? sizeof(Il2CppObject) : 0)); } while (0)
#define DEFAULTS_GEN_INIT(field, ns, n) do { il2cpp_defaults.field = Class::FromName (il2cpp_defaults.corlib_gen, ns, n);\
IL2CPP_ASSERT(il2cpp_defaults.field); } while (0)
#define DEFAULTS_GEN_INIT_TYPE(field, ns, n, nativetype) do { DEFAULTS_GEN_INIT(field, ns, n); \
IL2CPP_ASSERT(il2cpp_defaults.field->instance_size == sizeof(nativetype) + (il2cpp_defaults.field->byval_arg.valuetype ? sizeof(Il2CppObject) : 0)); } while (0)
#define DEFAULTS_GEN_INIT_OPTIONAL(field, ns, n) do { il2cpp_defaults.field = Class::FromName (il2cpp_defaults.corlib_gen, ns, n); } while (0)
char* basepath(const char* path)
{
std::string original_path(path);
size_t position_of_last_separator = original_path.find_last_of(IL2CPP_DIR_SEPARATOR);
return il2cpp::utils::StringUtils::StringDuplicate(original_path.substr(position_of_last_separator + 1).c_str());
}
static const char *framework_version_for(const char *runtime_version)
{
IL2CPP_ASSERT(runtime_version && "Invalid runtime version");
IL2CPP_ASSERT((strstr(runtime_version, "v4.0") == runtime_version) && "Invalid runtime version");
return "4.0";
}
static void SanityChecks()
{
#if IL2CPP_ENABLE_INTERLOCKED_64_REQUIRED_ALIGNMENT
IL2CPP_ASSERT(ALIGN_OF(int64_t) == 8);
#endif
}
static inline void InitializeStringEmpty()
{
Class::Init(il2cpp_defaults.string_class);
FieldInfo* stringEmptyField = Class::GetFieldFromName(il2cpp_defaults.string_class, "Empty");
Field::StaticSetValue(stringEmptyField, String::Empty());
}
static void SetConfigStr(const std::string& executablePath);
bool Runtime::Init(const char* domainName)
{
os::FastAutoLock lock(&s_InitLock);
IL2CPP_ASSERT(s_RuntimeInitCount >= 0);
if (s_RuntimeInitCount++ > 0)
return true;
SanityChecks();
#if IL2CPP_MONO_DEBUGGER
il2cpp::utils::Debugger::AllocateStaticData();
#endif
il2cpp::vm::Monitor::AllocateStaticData();
il2cpp::os::MemoryMappedFile::AllocateStaticData();
il2cpp::icalls::mscorlib::System::IO::MonoIO::AllocateStaticData();
il2cpp::vm::Class::AllocateStaticData();
#if IL2CPP_ENABLE_PROFILER
// Static data for profiler is initialised here and also when profiler is installed (Profiler::Install()) since il2cpp test setup differs from Unity
il2cpp::vm::Profiler::AllocateStaticData();
#endif
il2cpp::icalls::mscorlib::System::Reflection::RuntimeAssembly::AllocateStaticData();
os::Initialize();
os::Locale::Initialize();
MetadataAllocInitialize();
// NOTE(gab): the runtime_version needs to change once we
// will support multiple runtimes.
// For now we default to the one used by unity and don't
// allow the callers to change it.
s_FrameworkVersion = framework_version_for("v4.0.30319");
os::Image::Initialize();
os::Thread::Init();
#if IL2CPP_HAS_OS_SYNCHRONIZATION_CONTEXT
// Has to happen after Thread::Init() due to it needing a COM apartment on Windows
il2cpp::os::SynchronizationContext::Initialize();
#endif
// This should be filled in by generated code.
IL2CPP_ASSERT(g_CodegenRegistration != NULL);
g_CodegenRegistration();
if (!MetadataCache::Initialize())
{
s_RuntimeInitCount--;
return false;
}
Assembly::Initialize();
gc::GarbageCollector::Initialize();
// Thread needs GC initialized
Thread::Initialize();
register_allocator(il2cpp::utils::Memory::Malloc, il2cpp::utils::Memory::Free);
memset(&il2cpp_defaults, 0, sizeof(Il2CppDefaults));
const Il2CppAssembly* assembly = Assembly::Load("mscorlib.dll");
const Il2CppAssembly* assembly2 = Assembly::Load("__Generated");
// It is not possible to use DEFAULTS_INIT_TYPE for managed types for which we have a native struct, if the
// native struct does not map the complete managed type.
// Which is the case for: Il2CppThread, Il2CppAppDomain, Il2CppCultureInfo, Il2CppReflectionProperty,
// Il2CppDateTimeFormatInfo, Il2CppNumberFormatInfo
il2cpp_defaults.corlib = Assembly::GetImage(assembly);
il2cpp_defaults.corlib_gen = Assembly::GetImage(assembly2);
DEFAULTS_INIT(object_class, "System", "Object");
DEFAULTS_INIT(void_class, "System", "Void");
DEFAULTS_INIT_TYPE(boolean_class, "System", "Boolean", bool);
DEFAULTS_INIT_TYPE(byte_class, "System", "Byte", uint8_t);
DEFAULTS_INIT_TYPE(sbyte_class, "System", "SByte", int8_t);
DEFAULTS_INIT_TYPE(int16_class, "System", "Int16", int16_t);
DEFAULTS_INIT_TYPE(uint16_class, "System", "UInt16", uint16_t);
DEFAULTS_INIT_TYPE(int32_class, "System", "Int32", int32_t);
DEFAULTS_INIT_TYPE(uint32_class, "System", "UInt32", uint32_t);
DEFAULTS_INIT(uint_class, "System", "UIntPtr");
DEFAULTS_INIT_TYPE(int_class, "System", "IntPtr", intptr_t);
DEFAULTS_INIT_TYPE(int64_class, "System", "Int64", int64_t);
DEFAULTS_INIT_TYPE(uint64_class, "System", "UInt64", uint64_t);
DEFAULTS_INIT_TYPE(single_class, "System", "Single", float);
DEFAULTS_INIT_TYPE(double_class, "System", "Double", double);
DEFAULTS_INIT_TYPE(char_class, "System", "Char", Il2CppChar);
DEFAULTS_INIT(string_class, "System", "String");
DEFAULTS_INIT(enum_class, "System", "Enum");
DEFAULTS_INIT(array_class, "System", "Array");
DEFAULTS_INIT(value_type_class, "System", "ValueType");
DEFAULTS_INIT_TYPE(delegate_class, "System", "Delegate", Il2CppDelegate);
DEFAULTS_INIT_TYPE(multicastdelegate_class, "System", "MulticastDelegate", Il2CppMulticastDelegate);
DEFAULTS_INIT(asyncresult_class, "System.Runtime.Remoting.Messaging", "AsyncResult");
DEFAULTS_INIT_TYPE(async_call_class, "System", "MonoAsyncCall", Il2CppAsyncCall);
DEFAULTS_INIT(manualresetevent_class, "System.Threading", "ManualResetEvent");
//DEFAULTS_INIT(typehandle_class, "System", "RuntimeTypeHandle");
//DEFAULTS_INIT(methodhandle_class, "System", "RuntimeMethodHandle");
//DEFAULTS_INIT(fieldhandle_class, "System", "RuntimeFieldHandle");
DEFAULTS_INIT(systemtype_class, "System", "Type");
DEFAULTS_INIT_TYPE(monotype_class, "System", "MonoType", Il2CppReflectionMonoType);
//DEFAULTS_INIT(exception_class, "System", "Exception");
//DEFAULTS_INIT(threadabortexcepXtion_class, "System.Threading", "ThreadAbortException");
DEFAULTS_INIT_TYPE(thread_class, "System.Threading", "Thread", Il2CppThread);
DEFAULTS_INIT_TYPE(internal_thread_class, "System.Threading", "InternalThread", Il2CppInternalThread);
DEFAULTS_INIT_TYPE(runtimetype_class, "System", "RuntimeType", Il2CppReflectionRuntimeType);
DEFAULTS_INIT(appdomain_class, "System", "AppDomain");
DEFAULTS_INIT(appdomain_setup_class, "System", "AppDomainSetup");
DEFAULTS_INIT(member_info_class, "System.Reflection", "MemberInfo");
DEFAULTS_INIT(field_info_class, "System.Reflection", "FieldInfo");
DEFAULTS_INIT(method_info_class, "System.Reflection", "MethodInfo");
DEFAULTS_INIT(property_info_class, "System.Reflection", "PropertyInfo");
DEFAULTS_INIT_TYPE(event_info_class, "System.Reflection", "EventInfo", Il2CppReflectionEvent);
DEFAULTS_INIT_TYPE(stringbuilder_class, "System.Text", "StringBuilder", Il2CppStringBuilder);
DEFAULTS_INIT_TYPE(stack_frame_class, "System.Diagnostics", "StackFrame", Il2CppStackFrame);
DEFAULTS_INIT(stack_trace_class, "System.Diagnostics", "StackTrace");
DEFAULTS_INIT_TYPE(typed_reference_class, "System", "TypedReference", Il2CppTypedRef);
DEFAULTS_INIT(generic_ilist_class, "System.Collections.Generic", "IList`1");
DEFAULTS_INIT(generic_icollection_class, "System.Collections.Generic", "ICollection`1");
DEFAULTS_INIT(generic_ienumerable_class, "System.Collections.Generic", "IEnumerable`1");
DEFAULTS_INIT(generic_ireadonlylist_class, "System.Collections.Generic", "IReadOnlyList`1");
DEFAULTS_INIT(generic_ireadonlycollection_class, "System.Collections.Generic", "IReadOnlyCollection`1");
DEFAULTS_INIT(generic_nullable_class, "System", "Nullable`1");
DEFAULTS_INIT(version, "System", "Version");
DEFAULTS_INIT(culture_info, "System.Globalization", "CultureInfo");
DEFAULTS_INIT_TYPE(assembly_class, "System.Reflection", "RuntimeAssembly", Il2CppReflectionAssembly);
DEFAULTS_INIT_TYPE_OPTIONAL(assembly_name_class, "System.Reflection", "AssemblyName", Il2CppReflectionAssemblyName);
DEFAULTS_INIT_TYPE(parameter_info_class, "System.Reflection", "RuntimeParameterInfo", Il2CppReflectionParameter);
DEFAULTS_INIT_TYPE(module_class, "System.Reflection", "RuntimeModule", Il2CppReflectionModule);
DEFAULTS_INIT_TYPE(exception_class, "System", "Exception", Il2CppException);
DEFAULTS_INIT_TYPE(system_exception_class, "System", "SystemException", Il2CppSystemException);
DEFAULTS_INIT_TYPE(argument_exception_class, "System", "ArgumentException", Il2CppArgumentException);
DEFAULTS_INIT_TYPE(marshalbyrefobject_class, "System", "MarshalByRefObject", Il2CppMarshalByRefObject);
DEFAULTS_GEN_INIT_TYPE(il2cpp_com_object_class, "System", "__Il2CppComObject", Il2CppComObject);
DEFAULTS_INIT_TYPE(safe_handle_class, "System.Runtime.InteropServices", "SafeHandle", Il2CppSafeHandle);
DEFAULTS_INIT_TYPE(sort_key_class, "System.Globalization", "SortKey", Il2CppSortKey);
DEFAULTS_INIT(dbnull_class, "System", "DBNull");
DEFAULTS_INIT_TYPE_OPTIONAL(error_wrapper_class, "System.Runtime.InteropServices", "ErrorWrapper", Il2CppErrorWrapper);
DEFAULTS_INIT(missing_class, "System.Reflection", "Missing");
DEFAULTS_INIT(attribute_class, "System", "Attribute");
DEFAULTS_INIT_OPTIONAL(customattribute_data_class, "System.Reflection", "CustomAttributeData");
DEFAULTS_INIT_OPTIONAL(customattribute_typed_argument_class, "System.Reflection", "CustomAttributeTypedArgument");
DEFAULTS_INIT_OPTIONAL(customattribute_named_argument_class, "System.Reflection", "CustomAttributeNamedArgument");
DEFAULTS_INIT(key_value_pair_class, "System.Collections.Generic", "KeyValuePair`2");
DEFAULTS_INIT(system_guid_class, "System", "Guid");
DEFAULTS_INIT(threadpool_wait_callback_class, "System.Threading", "_ThreadPoolWaitCallback");
DEFAULTS_INIT(mono_method_message_class, "System.Runtime.Remoting.Messaging", "MonoMethodMessage");
il2cpp_defaults.threadpool_perform_wait_callback_method = (MethodInfo*)vm::Class::GetMethodFromName(
il2cpp_defaults.threadpool_wait_callback_class, "PerformWaitCallback", 0);
DEFAULTS_INIT_OPTIONAL(sbyte_shared_enum, "System", "SByteEnum");
DEFAULTS_INIT_OPTIONAL(int16_shared_enum, "System", "Int16Enum");
DEFAULTS_INIT_OPTIONAL(int32_shared_enum, "System", "Int32Enum");
DEFAULTS_INIT_OPTIONAL(int64_shared_enum, "System", "Int64Enum");
DEFAULTS_INIT_OPTIONAL(byte_shared_enum, "System", "ByteEnum");
DEFAULTS_INIT_OPTIONAL(uint16_shared_enum, "System", "UInt16Enum");
DEFAULTS_INIT_OPTIONAL(uint32_shared_enum, "System", "UInt32Enum");
DEFAULTS_INIT_OPTIONAL(uint64_shared_enum, "System", "UInt64Enum");
DEFAULTS_GEN_INIT_OPTIONAL(il2cpp_fully_shared_type, "Unity.IL2CPP.Metadata", "__Il2CppFullySharedGenericType");
DEFAULTS_GEN_INIT_OPTIONAL(il2cpp_fully_shared_struct_type, "Unity.IL2CPP.Metadata", "__Il2CppFullySharedGenericStructType");
ClassLibraryPAL::Initialize();
// Reflection needs GC initialized
Reflection::Initialize();
Image::InitNestedTypes(il2cpp_defaults.corlib);
const Il2CppAssembly* systemDll = Assembly::Load("System");
if (systemDll != NULL)
il2cpp_defaults.system_uri_class = Class::FromName(Assembly::GetImage(systemDll), "System", "Uri");
// This will only exist if there was at least 1 winmd file present during conversion
const Il2CppAssembly* windowsRuntimeMetadataAssembly = Assembly::Load("WindowsRuntimeMetadata");
if (windowsRuntimeMetadataAssembly != NULL)
{
const Il2CppImage* windowsRuntimeMetadataImage = Assembly::GetImage(windowsRuntimeMetadataAssembly);
il2cpp_defaults.ireference_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation", "IReference`1");
il2cpp_defaults.ireferencearray_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation", "IReferenceArray`1");
il2cpp_defaults.ikey_value_pair_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation.Collections", "IKeyValuePair`2");
il2cpp_defaults.ikey_value_pair_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation.Collections", "IKeyValuePair`2");
il2cpp_defaults.windows_foundation_uri_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation", "Uri");
il2cpp_defaults.windows_foundation_iuri_runtime_class_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation", "IUriRuntimeClass");
}
Class::Init(il2cpp_defaults.string_class);
os::Socket::Startup();
#if IL2CPP_MONO_DEBUGGER
il2cpp::utils::Debugger::Init();
#endif
Il2CppDomain* domain = Domain::GetCurrent();
Il2CppThread* mainThread = Thread::Attach(domain);
Thread::SetMain(mainThread);
Il2CppAppDomainSetup* setup = (Il2CppAppDomainSetup*)Object::NewPinned(il2cpp_defaults.appdomain_setup_class);
Il2CppAppDomain* ad = (Il2CppAppDomain*)Object::NewPinned(il2cpp_defaults.appdomain_class);
gc::WriteBarrier::GenericStore(&ad->data, domain);
gc::WriteBarrier::GenericStore(&domain->domain, ad);
gc::WriteBarrier::GenericStore(&domain->setup, setup);
domain->domain_id = 1; // Only have a single domain ATM.
domain->friendly_name = basepath(domainName);
LastError::InitializeLastErrorThreadStatic();
gc::GarbageCollector::InitializeFinalizer();
MetadataCache::InitializeGCSafe();
String::InitializeEmptyString(il2cpp_defaults.string_class);
InitializeStringEmpty();
g_il2cpp_is_fully_initialized = true;
// Force binary serialization in Mono to use reflection instead of code generation.
#undef SetEnvironmentVariable // Get rid of windows.h #define.
os::Environment::SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
os::Environment::SetEnvironmentVariable("MONO_XMLSERIALIZER_THS", "no");
Domain::ContextInit(domain);
Domain::ContextSet(domain->default_context);
VerifyApiVersion();
#if IL2CPP_MONO_DEBUGGER
il2cpp::utils::Debugger::Start();
#endif
std::string executablePath = os::Path::GetExecutablePath();
SetConfigStr(executablePath);
if (utils::Environment::GetNumMainArgs() == 0)
{
// If main args were never set, we default to 1 arg that is the executable path
const char* mainArgs[] = { executablePath.c_str() };
utils::Environment::SetMainArgs(mainArgs, 1);
}
hybridclr::Runtime::Initialize();
vm::MetadataCache::ExecuteEagerStaticClassConstructors();
vm::MetadataCache::ExecuteModuleInitializers();
#if !IL2CPP_MONO_DEBUGGER
il2cpp::utils::DebugSymbolReader::LoadDebugSymbols();
#endif
return true;
}
static Il2CppObject* GetEventArgsEmptyField()
{
Il2CppClass* eventArgsKlass = Class::FromName(il2cpp_defaults.corlib, "System", "EventArgs");
if (eventArgsKlass != NULL)
{
Class::Init(eventArgsKlass);
FieldInfo* emptyField = vm::Class::GetFieldFromName(eventArgsKlass, "Empty");
if (emptyField != NULL)
{
Il2CppObject* emptyValue;
vm::Field::StaticGetValue(emptyField, &emptyValue);
return emptyValue;
}
}
return NULL;
}
static void FireProcessExitEvent()
{
FieldInfo* processExitField = vm::Class::GetFieldFromName(il2cpp_defaults.appdomain_class, "ProcessExit");
if (processExitField != NULL) // The field might have been stripped, just ignore it.
{
Il2CppAppDomain* appDomain = vm::Domain::GetCurrent()->domain;
Il2CppDelegate* processExitDelegate;
vm::Field::GetValue((Il2CppObject*)appDomain, processExitField, &processExitDelegate);
if (processExitDelegate == NULL) // Don't call the delegate if no one is listening to it.
return;
void* args[2];
args[0] = appDomain;
args[1] = GetEventArgsEmptyField();
Il2CppException* unusedException;
Runtime::DelegateInvoke(processExitDelegate, args, &unusedException);
}
}
void Runtime::Shutdown()
{
os::FastAutoLock lock(&s_InitLock);
IL2CPP_ASSERT(s_RuntimeInitCount > 0);
if (--s_RuntimeInitCount > 0)
return;
FireProcessExitEvent();
shutting_down = true;
#if IL2CPP_MONO_DEBUGGER
il2cpp::utils::Debugger::RuntimeShutdownEnd();
#endif
il2cpp::icalls::mscorlib::System::Reflection::RuntimeAssembly::FreeStaticData();
#if IL2CPP_SUPPORT_THREADS
threadpool_ms_cleanup();
#endif
// Tries to abort all threads
// Threads at alertable waits may not have existing when this return
Thread::AbortAllThreads();
#if IL2CPP_ENABLE_PROFILER
il2cpp::vm::Profiler::Shutdown();
#endif
os::Socket::Cleanup();
String::CleanupEmptyString();
il2cpp::gc::GarbageCollector::UninitializeFinalizers();
// after the gc cleanup so the finalizer thread can unregister itself
Thread::Uninitialize();
#if IL2CPP_HAS_OS_SYNCHRONIZATION_CONTEXT
// Has to happen before os::Thread::Shutdown() due to it needing a COM apartment on Windows
il2cpp::os::SynchronizationContext::Shutdown();
#endif
os::Thread::Shutdown();
#if IL2CPP_ENABLE_RELOAD
MetadataCache::Clear();
#endif
// We need to do this before UninitializeGC because it uses (fixed) GC memory
Reflection::ClearStatics();
// We need to do this after thread shut down because it is freeing GC fixed memory
il2cpp::gc::GarbageCollector::UninitializeGC();
// This needs to happen after no managed code can run anymore, including GC finalizers
os::LibraryLoader::CleanupLoadedLibraries();
vm::Image::ClearCachedResourceData();
MetadataAllocCleanup();
vm::COMEntryPoints::FreeCachedData();
os::Locale::UnInitialize();
os::Uninitialize();
#if IL2CPP_ENABLE_PROFILER
il2cpp::vm::Profiler::FreeStaticData();
#endif
il2cpp::vm::Monitor::FreeStaticData();
il2cpp::os::MemoryMappedFile::FreeStaticData();
il2cpp::icalls::mscorlib::System::IO::MonoIO::FreeStaticData();
il2cpp::vm::Class::FreeStaticData();
#if IL2CPP_MONO_DEBUGGER
il2cpp::utils::Debugger::FreeStaticData();
#endif
#if IL2CPP_ENABLE_RELOAD
if (g_ClearMethodMetadataInitializedFlags != NULL)
g_ClearMethodMetadataInitializedFlags();
#endif
}
bool Runtime::IsShuttingDown()
{
return shutting_down;
}
void Runtime::SetConfigDir(const char *path)
{
s_ConfigDir = path;
}
static void SetConfigStr(const std::string& executablePath)
{
Il2CppDomain* domain = vm::Domain::GetCurrent();
std::string configFileName = utils::PathUtils::Basename(executablePath);
configFileName.append(".config");
std::string appBase = utils::PathUtils::DirectoryName(executablePath);
IL2CPP_OBJECT_SETREF(domain->setup, application_base, vm::String::New(appBase.c_str()));
IL2CPP_OBJECT_SETREF(domain->setup, configuration_file, vm::String::New(configFileName.c_str()));
}
void Runtime::SetConfigUtf16(const Il2CppChar* executablePath)
{
IL2CPP_ASSERT(executablePath);
std::string exePathUtf8 = il2cpp::utils::StringUtils::Utf16ToUtf8(executablePath);
SetConfigStr(exePathUtf8);
}
void Runtime::SetConfig(const char* executablePath)
{
IL2CPP_ASSERT(executablePath);
std::string executablePathStr(executablePath);
SetConfigStr(executablePathStr);
}
void Runtime::SetUnityTlsInterface(const void* unitytlsInterface)
{
s_UnitytlsInterface = unitytlsInterface;
}
const char *Runtime::GetFrameworkVersion()
{
return s_FrameworkVersion;
}
std::string Runtime::GetConfigDir()
{
if (s_ConfigDir.size() > 0)
return s_ConfigDir;
return utils::PathUtils::Combine(utils::Runtime::GetDataDir(), utils::StringView<char>("etc"));
}
const void* Runtime::GetUnityTlsInterface()
{
return s_UnitytlsInterface;
}
const MethodInfo* Runtime::GetDelegateInvoke(Il2CppClass* klass)
{
const MethodInfo* invoke = Class::GetMethodFromName(klass, "Invoke", -1);
IL2CPP_ASSERT(invoke);
return invoke;
}
Il2CppObject* Runtime::DelegateInvoke(Il2CppDelegate *delegate, void **params, Il2CppException **exc)
{
const MethodInfo* invoke = GetDelegateInvoke(delegate->object.klass);
return Invoke(invoke, delegate, params, exc);
}
Il2CppObject* Runtime::Invoke(const MethodInfo *method, void *obj, void **params, Il2CppException **exc)
{
if (exc)
il2cpp::gc::WriteBarrier::GenericStoreNull(exc);
// we wrap invoker call in try/catch here, rather than emitting a try/catch
// in every invoke call as that blows up the code size.
try
{
if ((method->flags & METHOD_ATTRIBUTE_STATIC) && method->klass && !method->klass->cctor_finished_or_no_cctor)
ClassInit(method->klass);
return InvokeWithThrow(method, obj, params);
}
catch (Il2CppExceptionWrapper& ex)
{
if (exc)
il2cpp::gc::WriteBarrier::GenericStore(exc, ex.ex);
return NULL;
}
}
Il2CppObject* Runtime::InvokeWithThrow(const MethodInfo *method, void *obj, void **params)
{
hybridclr::InitAndGetInterpreterDirectlyCallMethodPointer(method);
if (method->return_type->type == IL2CPP_TYPE_VOID)
{
method->invoker_method(method->methodPointer, method, obj, params, NULL);
return NULL;
}
else
{
if (method->return_type->valuetype)
{
Il2CppClass* returnType = Class::FromIl2CppType(method->return_type);
Class::Init(returnType);
void* returnValue = alloca(returnType->instance_size - sizeof(Il2CppObject));
method->invoker_method(method->methodPointer, method, obj, params, returnValue);
return Object::Box(returnType, returnValue);
}
else
{
// Note that here method->return_type might be a reference type or it might be
// a value type returned by reference.
void* returnValue = NULL;
method->invoker_method(method->methodPointer, method, obj, params, &returnValue);
if (method->return_type->byref)
{
// We cannot use method->return_type->valuetype here, because that will be
// false for methods that return by reference. Instead, get the class for the
// type, which discards the byref flag.
Il2CppClass* returnType = Class::FromIl2CppType(method->return_type);
if (vm::Class::IsValuetype(returnType))
return Object::Box(returnType, returnValue);
return *(Il2CppObject**)returnValue;
}
return (Il2CppObject*)returnValue;
}
}
}
Il2CppObject* Runtime::InvokeArray(const MethodInfo *method, void *obj, Il2CppArray *params, Il2CppException **exc)
{
if (params == NULL)
return InvokeConvertArgs(method, obj, NULL, 0, exc);
// TO DO: when changing GC to one that moves managed objects around, mark params array local variable as pinned!
return InvokeConvertArgs(method, obj, reinterpret_cast<Il2CppObject**>(Array::GetFirstElementAddress(params)), Array::GetLength(params), exc);
}
void Runtime::ObjectInit(Il2CppObject *object)
{
ObjectInitException(object, NULL);
}
void Runtime::ObjectInitException(Il2CppObject *object, Il2CppException **exc)
{
const MethodInfo *method = NULL;
Il2CppClass *klass = object->klass;
method = Class::GetMethodFromName(klass, ".ctor", 0);
IL2CPP_ASSERT(method != NULL && "ObjectInit; no default constructor for object is found");
if (method->klass->byval_arg.valuetype)
object = (Il2CppObject*)Object::Unbox(object);
Invoke(method, object, NULL, exc);
}
void Runtime::SetUnhandledExceptionPolicy(Il2CppRuntimeUnhandledExceptionPolicy value)
{
s_UnhandledExceptionPolicy = value;
}
Il2CppRuntimeUnhandledExceptionPolicy Runtime::GetUnhandledExceptionPolicy()
{
return s_UnhandledExceptionPolicy;
}
void Runtime::UnhandledException(Il2CppException* exc)
{
Il2CppDomain *currentDomain = Domain::GetCurrent();
Il2CppDomain *rootDomain = Domain::GetRoot();
FieldInfo *field;
Il2CppObject *current_appdomain_delegate = NULL;
Il2CppObject *root_appdomain_delegate = NULL;
field = Class::GetFieldFromName(il2cpp_defaults.appdomain_class, "UnhandledException");
IL2CPP_ASSERT(field);
Il2CppObject* excObject = (Il2CppObject*)exc;
if (excObject->klass != il2cpp_defaults.threadabortexception_class)
{
//bool abort_process = (Thread::Current () == Thread::Main ()) ||
// (Runtime::GetUnhandledExceptionPolicy () == IL2CPP_UNHANDLED_POLICY_CURRENT);
Field::GetValue((Il2CppObject*)rootDomain->domain, field, &root_appdomain_delegate);
IL2CPP_NOT_IMPLEMENTED_NO_ASSERT(Runtime::UnhandledException, "We don't have runtime version info yet");
//if (currentDomain != rootDomain && (mono_framework_version () >= 2)) {
// Field::GetValue ((Il2CppObject*)currentDomain->domain, field, ¤t_appdomain_delegate);
//}
//else
//{
// current_appdomain_delegate = NULL;
//}
///* set exitcode only if we will abort the process */
//if (abort_process)
// mono_environment_exitcode_set (1);
//if ((current_appdomain_delegate == NULL) && (root_appdomain_delegate == NULL)
//{
// mono_print_unhandled_exception (exc);
//}
//else
{
if (root_appdomain_delegate)
{
CallUnhandledExceptionDelegate(rootDomain, (Il2CppDelegate*)root_appdomain_delegate, exc);
}
if (current_appdomain_delegate)
{
CallUnhandledExceptionDelegate(currentDomain, (Il2CppDelegate*)current_appdomain_delegate, exc);
}
}
}
}
static inline Il2CppObject* InvokeConvertThis(const MethodInfo* method, void* thisArg, void** convertedParameters, Il2CppException** exception)
{
Il2CppClass* thisType = method->klass;
// If it's not a constructor, just invoke directly
if (strcmp(method->name, ".ctor") != 0 || method->klass == il2cpp_defaults.string_class)
{
void* obj = thisArg;
if (Class::IsNullable(method->klass))
{
Il2CppObject* nullable;
/* Convert the unboxed vtype into a Nullable structure */
nullable = Object::New(method->klass);
Il2CppObject* boxed = Object::Box(method->klass->castClass, obj);
Object::NullableInit((uint8_t*)Object::Unbox(nullable), boxed, method->klass);
obj = Object::Unbox(nullable);
}
return Runtime::Invoke(method, obj, convertedParameters, exception);
}
// If it is a construction, we need to construct a return value and allocate object if needed
Il2CppObject* instance;
if (thisArg == NULL)
{
if (Class::IsNullable(thisType))
{
// in the case of a Nullable constructor we can just return a boxed value type
IL2CPP_ASSERT(convertedParameters);
instance = Object::Box(thisType->castClass, convertedParameters[0]);
}
else
{
thisArg = instance = Object::New(thisType);
Runtime::Invoke(method, thisType->byval_arg.valuetype ? Object::Unbox((Il2CppObject*)thisArg) : thisArg, convertedParameters, exception);
}
}
else
{
// thisArg is pointer to data in case of a value type
// We need to invoke the constructor first, passing point to the value
// Since the constructor may modify the value, we need to box the result
// AFTER the constructor was invoked
Runtime::Invoke(method, thisArg, convertedParameters, exception);
instance = Object::Box(thisType, thisArg);
}
return instance;
}
Il2CppObject* Runtime::InvokeConvertArgs(const MethodInfo *method, void* thisArg, Il2CppObject** parameters, int paramCount, Il2CppException** exception)
{
void** convertedParameters = NULL;
bool hasByRefNullables = false;
// Convert parameters if they are not null
if (parameters != NULL)
{
convertedParameters = (void**)alloca(sizeof(void*) * paramCount);
for (int i = 0; i < paramCount; i++)
{
bool passedByReference = method->parameters[i]->byref;
Il2CppClass* parameterType = Class::FromIl2CppType(method->parameters[i]);
Class::Init(parameterType);
if (Class::IsValuetype(parameterType))
{
if (Class::IsNullable(parameterType))
{
// Since we don't really store boxed nullables, we need to create a new one.
void* nullableStorage = alloca(parameterType->instance_size - sizeof(Il2CppObject));
Object::UnboxNullable(parameters[i], parameterType, nullableStorage);
convertedParameters[i] = nullableStorage;
hasByRefNullables |= passedByReference;
}
else if (passedByReference)
{
// If value type is passed by reference, just pass pointer to value directly
// If null was passed in, create a new boxed value type in its place
if (parameters[i] == NULL)
gc::WriteBarrier::GenericStore(parameters + i, Object::New(parameterType));
convertedParameters[i] = Object::Unbox(parameters[i]);
}
else if (parameters[i] == NULL) // If value type is passed by value, we need to pass pointer to its value
{
// If null was passed in, allocate a new value with default value
uint32_t valueSize = parameterType->instance_size - sizeof(Il2CppObject);
convertedParameters[i] = alloca(valueSize);
memset(convertedParameters[i], 0, valueSize);
}
else
{
// Otherwise, pass the original
convertedParameters[i] = Object::Unbox(parameters[i]);
}
}
else if (passedByReference)
{
convertedParameters[i] = ¶meters[i]; // Reference type passed by reference
}
else if (parameterType->byval_arg.type == IL2CPP_TYPE_PTR)
{
if (parameters[i] != NULL)
{
IL2CPP_ASSERT(parameters[i]->klass == il2cpp_defaults.int_class);
convertedParameters[i] = reinterpret_cast<void*>(*static_cast<intptr_t*>(Object::Unbox(parameters[i])));
}
else
{
convertedParameters[i] = NULL;
}
}
else
{
convertedParameters[i] = parameters[i]; // Reference type passed by value
}
}
}
Il2CppObject* result = InvokeConvertThis(method, thisArg, convertedParameters, exception);
if (hasByRefNullables)
{
// We need to copy by reference nullables back to original argument array
for (int i = 0; i < paramCount; i++)
{
if (!method->parameters[i]->byref)
continue;
Il2CppClass* parameterType = Class::FromIl2CppType(method->parameters[i]);
if (Class::IsNullable(parameterType))
gc::WriteBarrier::GenericStore(parameters + i, Object::Box(parameterType, convertedParameters[i]));
}
}
if (method->return_type->type == IL2CPP_TYPE_PTR)
{
static Il2CppClass* pointerClass = Class::FromName(il2cpp_defaults.corlib, "System.Reflection", "Pointer");
Il2CppReflectionPointer* pointer = reinterpret_cast<Il2CppReflectionPointer*>(Object::New(pointerClass));
pointer->data = result;
IL2CPP_OBJECT_SETREF(pointer, type, Reflection::GetTypeObject(method->return_type));
result = reinterpret_cast<Il2CppObject*>(pointer);
}
return result;
}
void Runtime::CallUnhandledExceptionDelegate(Il2CppDomain* domain, Il2CppDelegate* delegate, Il2CppException* exc)
{
Il2CppException *e = NULL;
void* pa[2];
pa[0] = domain->domain;
pa[1] = CreateUnhandledExceptionEventArgs(exc);
DelegateInvoke(delegate, pa, &e);
// A managed exception occurred during the unhandled exception handler.
// We can't do much else here other than try to abort the process.
if (e != NULL)
utils::Runtime::Abort();
}
static baselib::ReentrantLock s_TypeInitializationLock;
// We currently call Runtime::ClassInit in 4 places:
// 1. Just after we allocate storage for a new object (Object::NewAllocSpecific)
// 2. Just before reading any static field
// 3. Just before calling any static method
// 4. Just before calling class instance constructor from a derived class instance constructor
void Runtime::ClassInit(Il2CppClass *klass)
{
// Nothing to do if class has no static constructor or already ran.
if (klass->cctor_finished_or_no_cctor)
return;
s_TypeInitializationLock.Acquire();
// See if some thread ran it while we acquired the lock.
if (os::Atomic::CompareExchange(&klass->cctor_finished_or_no_cctor, 1, 1) == 1)
{
s_TypeInitializationLock.Release();
return;
}
// See if some other thread got there first and already started running the constructor.
if (os::Atomic::CompareExchange(&klass->cctor_started, 1, 1) == 1)
{
s_TypeInitializationLock.Release();
// May have been us and we got here through recursion.
os::Thread::ThreadId currentThread = os::Thread::CurrentThreadId();
if (os::Atomic::CompareExchangePointer((size_t**)&klass->cctor_thread, (size_t*)currentThread, (size_t*)currentThread) == (size_t*)currentThread)
return;
// Wait for other thread to finish executing the constructor.
while (os::Atomic::CompareExchange(&klass->cctor_finished_or_no_cctor, 1, 1) != 1 && os::Atomic::CompareExchangePointer((void**)&klass->initializationExceptionGCHandle, (void*)0, (void*)0) == 0)
{
os::Thread::Sleep(1);
}
}
else
{
// Let others know we have started executing the constructor.
os::Atomic::ExchangePointer((size_t**)&klass->cctor_thread, (size_t*)os::Thread::CurrentThreadId());
os::Atomic::Exchange(&klass->cctor_started, 1);
s_TypeInitializationLock.Release();
// Run it.
Il2CppException* exception = NULL;
const MethodInfo* cctor = Class::GetCCtor(klass);
if (cctor != NULL)
{
vm::Runtime::Invoke(cctor, NULL, NULL, &exception);
}
os::Atomic::ExchangePointer((size_t**)&klass->cctor_thread, (size_t*)0);
// Deal with exceptions.
if (exception == NULL)
{
// Let other threads know we finished.
os::Atomic::Exchange(&klass->cctor_finished_or_no_cctor, 1);
}
else
{
const Il2CppType *type = Class::GetType(klass);
std::string n = il2cpp::utils::StringUtils::Printf("The type initializer for '%s' threw an exception.", Type::GetName(type, IL2CPP_TYPE_NAME_FORMAT_IL).c_str());
Class::SetClassInitializationError(klass, Exception::GetTypeInitializationException(n.c_str(), exception));
}
}
if (klass->initializationExceptionGCHandle)
{
il2cpp::vm::Exception::Raise((Il2CppException*)gc::GCHandle::GetTarget(klass->initializationExceptionGCHandle));
}
}
struct ConstCharCompare
{
bool operator()(char const *a, char const *b) const
{
return strcmp(a, b) < 0;
}