Runtime.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. #include "il2cpp-config.h"
  2. #include "metadata/GenericMethod.h"
  3. #include "os/CrashHelpers.h"
  4. #include "os/Environment.h"
  5. #include "os/File.h"
  6. #include "os/Image.h"
  7. #include "os/Initialize.h"
  8. #include "os/LibraryLoader.h"
  9. #include "os/Locale.h"
  10. #include "os/MemoryMappedFile.h"
  11. #include "os/Mutex.h"
  12. #include "os/Path.h"
  13. #include "os/SynchronizationContext.h"
  14. #include "os/Thread.h"
  15. #include "os/Socket.h"
  16. #include "os/c-api/Allocator.h"
  17. #include "metadata/GenericMetadata.h"
  18. #include "vm/Array.h"
  19. #include "vm/Assembly.h"
  20. #include "vm/ClassLibraryPAL.h"
  21. #include "vm/COMEntryPoints.h"
  22. #include "vm/Class.h"
  23. #include "vm/Domain.h"
  24. #include "vm/Exception.h"
  25. #include "vm/Field.h"
  26. #include "gc/GCHandle.h"
  27. #include "vm/Image.h"
  28. #include "vm/LastError.h"
  29. #include "vm/MetadataAlloc.h"
  30. #include "vm/MetadataCache.h"
  31. #include "vm/MetadataLock.h"
  32. #include "vm/Method.h"
  33. #include "vm/Reflection.h"
  34. #include "vm/Runtime.h"
  35. #include "vm/Thread.h"
  36. #include "vm/Type.h"
  37. #include "vm/StackTrace.h"
  38. #include "vm/String.h"
  39. #include "vm/Object.h"
  40. #include "vm-utils/Debugger.h"
  41. #include "vm-utils/DebugSymbolReader.h"
  42. #include "vm/Profiler.h"
  43. #include "utils/Logging.h"
  44. #include <string>
  45. #include <map>
  46. #include "il2cpp-class-internals.h"
  47. #include "il2cpp-object-internals.h"
  48. #include "il2cpp-tabledefs.h"
  49. #include "gc/GarbageCollector.h"
  50. #include "gc/WriteBarrier.h"
  51. #include "vm/InternalCalls.h"
  52. #include "utils/Collections.h"
  53. #include "utils/Memory.h"
  54. #include "utils/StringUtils.h"
  55. #include "utils/PathUtils.h"
  56. #include "utils/Runtime.h"
  57. #include "utils/Environment.h"
  58. #include "mono/ThreadPool/threadpool-ms.h"
  59. #include "mono/ThreadPool/threadpool-ms-io.h"
  60. //#include "icalls/mscorlib/System.Reflection/Assembly.h"
  61. #include "Baselib.h"
  62. #include "Cpp/ReentrantLock.h"
  63. #if IL2CPP_MONO_DEBUGGER
  64. extern "C" {
  65. #include <mono/metadata/profiler-private.h>
  66. }
  67. #endif
  68. #include "hybridclr/Runtime.h"
  69. #include "hybridclr/Il2CppCompatibleDef.h"
  70. Il2CppDefaults il2cpp_defaults;
  71. bool g_il2cpp_is_fully_initialized = false;
  72. static bool shutting_down = false;
  73. MetadataInitializerCleanupFunc g_ClearMethodMetadataInitializedFlags = NULL;
  74. static baselib::ReentrantLock s_InitLock;
  75. static int32_t s_RuntimeInitCount;
  76. typedef void (*CodegenRegistrationFunction) ();
  77. extern CodegenRegistrationFunction g_CodegenRegistration;
  78. namespace il2cpp
  79. {
  80. namespace vm
  81. {
  82. baselib::ReentrantLock g_MetadataLock;
  83. static int32_t exitcode = 0;
  84. static std::string s_ConfigDir;
  85. static const char *s_FrameworkVersion = 0;
  86. static const char *s_BundledMachineConfig = 0;
  87. static Il2CppRuntimeUnhandledExceptionPolicy s_UnhandledExceptionPolicy = IL2CPP_UNHANDLED_POLICY_CURRENT;
  88. static const void* s_UnitytlsInterface = NULL;
  89. #define DEFAULTS_INIT(field, ns, n) do { il2cpp_defaults.field = Class::FromName (il2cpp_defaults.corlib, ns, n);\
  90. IL2CPP_ASSERT(il2cpp_defaults.field); } while (0)
  91. #define DEFAULTS_INIT_TYPE(field, ns, n, nativetype) do { DEFAULTS_INIT(field, ns, n); \
  92. IL2CPP_ASSERT(il2cpp_defaults.field->instance_size == sizeof(nativetype) + (il2cpp_defaults.field->byval_arg.valuetype ? sizeof(Il2CppObject) : 0)); } while (0)
  93. #define DEFAULTS_INIT_OPTIONAL(field, ns, n) do { il2cpp_defaults.field = Class::FromName (il2cpp_defaults.corlib, ns, n); } while (0)
  94. #define DEFAULTS_INIT_TYPE_OPTIONAL(field, ns, n, nativetype) do { DEFAULTS_INIT_OPTIONAL(field, ns, n); \
  95. if (il2cpp_defaults.field != NULL) \
  96. IL2CPP_ASSERT(il2cpp_defaults.field->instance_size == sizeof(nativetype) + (il2cpp_defaults.field->byval_arg.valuetype ? sizeof(Il2CppObject) : 0)); } while (0)
  97. #define DEFAULTS_GEN_INIT(field, ns, n) do { il2cpp_defaults.field = Class::FromName (il2cpp_defaults.corlib_gen, ns, n);\
  98. IL2CPP_ASSERT(il2cpp_defaults.field); } while (0)
  99. #define DEFAULTS_GEN_INIT_TYPE(field, ns, n, nativetype) do { DEFAULTS_GEN_INIT(field, ns, n); \
  100. IL2CPP_ASSERT(il2cpp_defaults.field->instance_size == sizeof(nativetype) + (il2cpp_defaults.field->byval_arg.valuetype ? sizeof(Il2CppObject) : 0)); } while (0)
  101. #define DEFAULTS_GEN_INIT_OPTIONAL(field, ns, n) do { il2cpp_defaults.field = Class::FromName (il2cpp_defaults.corlib_gen, ns, n); } while (0)
  102. char* basepath(const char* path)
  103. {
  104. std::string original_path(path);
  105. size_t position_of_last_separator = original_path.find_last_of(IL2CPP_DIR_SEPARATOR);
  106. return il2cpp::utils::StringUtils::StringDuplicate(original_path.substr(position_of_last_separator + 1).c_str());
  107. }
  108. static const char *framework_version_for(const char *runtime_version)
  109. {
  110. IL2CPP_ASSERT(runtime_version && "Invalid runtime version");
  111. IL2CPP_ASSERT((strstr(runtime_version, "v4.0") == runtime_version) && "Invalid runtime version");
  112. return "4.0";
  113. }
  114. static void SanityChecks()
  115. {
  116. #if IL2CPP_ENABLE_INTERLOCKED_64_REQUIRED_ALIGNMENT
  117. IL2CPP_ASSERT(ALIGN_OF(int64_t) == 8);
  118. #endif
  119. }
  120. static inline void InitializeStringEmpty()
  121. {
  122. Class::Init(il2cpp_defaults.string_class);
  123. FieldInfo* stringEmptyField = Class::GetFieldFromName(il2cpp_defaults.string_class, "Empty");
  124. Field::StaticSetValue(stringEmptyField, String::Empty());
  125. }
  126. static void SetConfigStr(const std::string& executablePath);
  127. bool Runtime::Init(const char* domainName)
  128. {
  129. os::FastAutoLock lock(&s_InitLock);
  130. IL2CPP_ASSERT(s_RuntimeInitCount >= 0);
  131. if (s_RuntimeInitCount++ > 0)
  132. return true;
  133. SanityChecks();
  134. os::Initialize();
  135. os::Locale::Initialize();
  136. MetadataAllocInitialize();
  137. // NOTE(gab): the runtime_version needs to change once we
  138. // will support multiple runtimes.
  139. // For now we default to the one used by unity and don't
  140. // allow the callers to change it.
  141. s_FrameworkVersion = framework_version_for("v4.0.30319");
  142. os::Image::Initialize();
  143. os::Thread::Init();
  144. #if !IL2CPP_TINY && !IL2CPP_MONO_DEBUGGER
  145. il2cpp::utils::DebugSymbolReader::LoadDebugSymbols();
  146. #endif
  147. #if IL2CPP_HAS_OS_SYNCHRONIZATION_CONTEXT
  148. // Has to happen after Thread::Init() due to it needing a COM apartment on Windows
  149. il2cpp::os::SynchronizationContext::Initialize();
  150. #endif
  151. // This should be filled in by generated code.
  152. IL2CPP_ASSERT(g_CodegenRegistration != NULL);
  153. g_CodegenRegistration();
  154. if (!MetadataCache::Initialize())
  155. {
  156. s_RuntimeInitCount--;
  157. return false;
  158. }
  159. Assembly::Initialize();
  160. gc::GarbageCollector::Initialize();
  161. // Thread needs GC initialized
  162. Thread::Initialize();
  163. register_allocator(il2cpp::utils::Memory::Malloc);
  164. memset(&il2cpp_defaults, 0, sizeof(Il2CppDefaults));
  165. const Il2CppAssembly* assembly = Assembly::Load("mscorlib.dll");
  166. const Il2CppAssembly* assembly2 = Assembly::Load("__Generated");
  167. // It is not possible to use DEFAULTS_INIT_TYPE for managed types for which we have a native struct, if the
  168. // native struct does not map the complete managed type.
  169. // Which is the case for: Il2CppThread, Il2CppAppDomain, Il2CppCultureInfo, Il2CppReflectionProperty,
  170. // Il2CppDateTimeFormatInfo, Il2CppNumberFormatInfo
  171. il2cpp_defaults.corlib = Assembly::GetImage(assembly);
  172. il2cpp_defaults.corlib_gen = Assembly::GetImage(assembly2);
  173. DEFAULTS_INIT(object_class, "System", "Object");
  174. DEFAULTS_INIT(void_class, "System", "Void");
  175. DEFAULTS_INIT_TYPE(boolean_class, "System", "Boolean", bool);
  176. DEFAULTS_INIT_TYPE(byte_class, "System", "Byte", uint8_t);
  177. DEFAULTS_INIT_TYPE(sbyte_class, "System", "SByte", int8_t);
  178. DEFAULTS_INIT_TYPE(int16_class, "System", "Int16", int16_t);
  179. DEFAULTS_INIT_TYPE(uint16_class, "System", "UInt16", uint16_t);
  180. DEFAULTS_INIT_TYPE(int32_class, "System", "Int32", int32_t);
  181. DEFAULTS_INIT_TYPE(uint32_class, "System", "UInt32", uint32_t);
  182. DEFAULTS_INIT(uint_class, "System", "UIntPtr");
  183. DEFAULTS_INIT_TYPE(int_class, "System", "IntPtr", intptr_t);
  184. DEFAULTS_INIT_TYPE(int64_class, "System", "Int64", int64_t);
  185. DEFAULTS_INIT_TYPE(uint64_class, "System", "UInt64", uint64_t);
  186. DEFAULTS_INIT_TYPE(single_class, "System", "Single", float);
  187. DEFAULTS_INIT_TYPE(double_class, "System", "Double", double);
  188. DEFAULTS_INIT_TYPE(char_class, "System", "Char", Il2CppChar);
  189. DEFAULTS_INIT(string_class, "System", "String");
  190. DEFAULTS_INIT(enum_class, "System", "Enum");
  191. DEFAULTS_INIT(array_class, "System", "Array");
  192. DEFAULTS_INIT(value_type_class, "System", "ValueType");
  193. #if !IL2CPP_TINY
  194. DEFAULTS_INIT_TYPE(delegate_class, "System", "Delegate", Il2CppDelegate);
  195. DEFAULTS_INIT_TYPE(multicastdelegate_class, "System", "MulticastDelegate", Il2CppMulticastDelegate);
  196. DEFAULTS_INIT(asyncresult_class, "System.Runtime.Remoting.Messaging", "AsyncResult");
  197. DEFAULTS_INIT_TYPE(async_call_class, "System", "MonoAsyncCall", Il2CppAsyncCall);
  198. DEFAULTS_INIT(manualresetevent_class, "System.Threading", "ManualResetEvent");
  199. #endif // !IL2CPP_TINY
  200. //DEFAULTS_INIT(typehandle_class, "System", "RuntimeTypeHandle");
  201. //DEFAULTS_INIT(methodhandle_class, "System", "RuntimeMethodHandle");
  202. //DEFAULTS_INIT(fieldhandle_class, "System", "RuntimeFieldHandle");
  203. DEFAULTS_INIT(systemtype_class, "System", "Type");
  204. #if !IL2CPP_TINY
  205. DEFAULTS_INIT_TYPE(monotype_class, "System", "MonoType", Il2CppReflectionMonoType);
  206. #endif
  207. //DEFAULTS_INIT(exception_class, "System", "Exception");
  208. //DEFAULTS_INIT(threadabortexcepXtion_class, "System.Threading", "ThreadAbortException");
  209. DEFAULTS_INIT_TYPE(thread_class, "System.Threading", "Thread", Il2CppThread);
  210. DEFAULTS_INIT_TYPE(internal_thread_class, "System.Threading", "InternalThread", Il2CppInternalThread);
  211. DEFAULTS_INIT_TYPE(runtimetype_class, "System", "RuntimeType", Il2CppReflectionRuntimeType);
  212. #if !IL2CPP_TINY
  213. DEFAULTS_INIT(appdomain_class, "System", "AppDomain");
  214. DEFAULTS_INIT(appdomain_setup_class, "System", "AppDomainSetup");
  215. DEFAULTS_INIT(member_info_class, "System.Reflection", "MemberInfo");
  216. DEFAULTS_INIT(field_info_class, "System.Reflection", "FieldInfo");
  217. DEFAULTS_INIT(method_info_class, "System.Reflection", "MethodInfo");
  218. DEFAULTS_INIT(property_info_class, "System.Reflection", "PropertyInfo");
  219. DEFAULTS_INIT_TYPE(event_info_class, "System.Reflection", "EventInfo", Il2CppReflectionEvent);
  220. DEFAULTS_INIT_TYPE(stringbuilder_class, "System.Text", "StringBuilder", Il2CppStringBuilder);
  221. DEFAULTS_INIT_TYPE(stack_frame_class, "System.Diagnostics", "StackFrame", Il2CppStackFrame);
  222. DEFAULTS_INIT(stack_trace_class, "System.Diagnostics", "StackTrace");
  223. DEFAULTS_INIT_TYPE(typed_reference_class, "System", "TypedReference", Il2CppTypedRef);
  224. #endif
  225. DEFAULTS_INIT(generic_ilist_class, "System.Collections.Generic", "IList`1");
  226. DEFAULTS_INIT(generic_icollection_class, "System.Collections.Generic", "ICollection`1");
  227. DEFAULTS_INIT(generic_ienumerable_class, "System.Collections.Generic", "IEnumerable`1");
  228. DEFAULTS_INIT(generic_ireadonlylist_class, "System.Collections.Generic", "IReadOnlyList`1");
  229. DEFAULTS_INIT(generic_ireadonlycollection_class, "System.Collections.Generic", "IReadOnlyCollection`1");
  230. DEFAULTS_INIT(generic_nullable_class, "System", "Nullable`1");
  231. #if !IL2CPP_TINY
  232. DEFAULTS_INIT(version, "System", "Version");
  233. DEFAULTS_INIT(culture_info, "System.Globalization", "CultureInfo");
  234. DEFAULTS_INIT_TYPE(assembly_class, "System.Reflection", "RuntimeAssembly", Il2CppReflectionAssembly);
  235. DEFAULTS_INIT_TYPE_OPTIONAL(assembly_name_class, "System.Reflection", "AssemblyName", Il2CppReflectionAssemblyName);
  236. DEFAULTS_INIT_TYPE(parameter_info_class, "System.Reflection", "RuntimeParameterInfo", Il2CppReflectionParameter);
  237. DEFAULTS_INIT_TYPE(module_class, "System.Reflection", "RuntimeModule", Il2CppReflectionModule);
  238. DEFAULTS_INIT_TYPE(exception_class, "System", "Exception", Il2CppException);
  239. DEFAULTS_INIT_TYPE(system_exception_class, "System", "SystemException", Il2CppSystemException);
  240. DEFAULTS_INIT_TYPE(argument_exception_class, "System", "ArgumentException", Il2CppArgumentException);
  241. DEFAULTS_INIT_TYPE(marshalbyrefobject_class, "System", "MarshalByRefObject", Il2CppMarshalByRefObject);
  242. DEFAULTS_GEN_INIT_TYPE(il2cpp_com_object_class, "System", "__Il2CppComObject", Il2CppComObject);
  243. DEFAULTS_INIT_TYPE(safe_handle_class, "System.Runtime.InteropServices", "SafeHandle", Il2CppSafeHandle);
  244. DEFAULTS_INIT_TYPE(sort_key_class, "System.Globalization", "SortKey", Il2CppSortKey);
  245. DEFAULTS_INIT(dbnull_class, "System", "DBNull");
  246. DEFAULTS_INIT_TYPE_OPTIONAL(error_wrapper_class, "System.Runtime.InteropServices", "ErrorWrapper", Il2CppErrorWrapper);
  247. DEFAULTS_INIT(missing_class, "System.Reflection", "Missing");
  248. DEFAULTS_INIT(attribute_class, "System", "Attribute");
  249. DEFAULTS_INIT_OPTIONAL(customattribute_data_class, "System.Reflection", "CustomAttributeData");
  250. DEFAULTS_INIT_OPTIONAL(customattribute_typed_argument_class, "System.Reflection", "CustomAttributeTypedArgument");
  251. DEFAULTS_INIT_OPTIONAL(customattribute_named_argument_class, "System.Reflection", "CustomAttributeNamedArgument");
  252. DEFAULTS_INIT(key_value_pair_class, "System.Collections.Generic", "KeyValuePair`2");
  253. DEFAULTS_INIT(system_guid_class, "System", "Guid");
  254. #endif // !IL2CPP_TINY
  255. #if !IL2CPP_TINY
  256. DEFAULTS_INIT(threadpool_wait_callback_class, "System.Threading", "_ThreadPoolWaitCallback");
  257. DEFAULTS_INIT(mono_method_message_class, "System.Runtime.Remoting.Messaging", "MonoMethodMessage");
  258. il2cpp_defaults.threadpool_perform_wait_callback_method = (MethodInfo*)vm::Class::GetMethodFromName(
  259. il2cpp_defaults.threadpool_wait_callback_class, "PerformWaitCallback", 0);
  260. #endif
  261. DEFAULTS_INIT_OPTIONAL(sbyte_shared_enum, "System", "SByteEnum");
  262. DEFAULTS_INIT_OPTIONAL(int16_shared_enum, "System", "Int16Enum");
  263. DEFAULTS_INIT_OPTIONAL(int32_shared_enum, "System", "Int32Enum");
  264. DEFAULTS_INIT_OPTIONAL(int64_shared_enum, "System", "Int64Enum");
  265. DEFAULTS_INIT_OPTIONAL(byte_shared_enum, "System", "ByteEnum");
  266. DEFAULTS_INIT_OPTIONAL(uint16_shared_enum, "System", "UInt16Enum");
  267. DEFAULTS_INIT_OPTIONAL(uint32_shared_enum, "System", "UInt32Enum");
  268. DEFAULTS_INIT_OPTIONAL(uint64_shared_enum, "System", "UInt64Enum");
  269. DEFAULTS_GEN_INIT_OPTIONAL(il2cpp_fully_shared_type, "Unity.IL2CPP.Metadata", "__Il2CppFullySharedGenericType");
  270. DEFAULTS_GEN_INIT_OPTIONAL(il2cpp_fully_shared_struct_type, "Unity.IL2CPP.Metadata", "__Il2CppFullySharedGenericStructType");
  271. ClassLibraryPAL::Initialize();
  272. // Reflection needs GC initialized
  273. Reflection::Initialize();
  274. Image::InitNestedTypes(il2cpp_defaults.corlib);
  275. const Il2CppAssembly* systemDll = Assembly::Load("System");
  276. if (systemDll != NULL)
  277. il2cpp_defaults.system_uri_class = Class::FromName(Assembly::GetImage(systemDll), "System", "Uri");
  278. // This will only exist if there was at least 1 winmd file present during conversion
  279. const Il2CppAssembly* windowsRuntimeMetadataAssembly = Assembly::Load("WindowsRuntimeMetadata");
  280. if (windowsRuntimeMetadataAssembly != NULL)
  281. {
  282. const Il2CppImage* windowsRuntimeMetadataImage = Assembly::GetImage(windowsRuntimeMetadataAssembly);
  283. il2cpp_defaults.ireference_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation", "IReference`1");
  284. il2cpp_defaults.ireferencearray_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation", "IReferenceArray`1");
  285. il2cpp_defaults.ikey_value_pair_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation.Collections", "IKeyValuePair`2");
  286. il2cpp_defaults.ikey_value_pair_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation.Collections", "IKeyValuePair`2");
  287. il2cpp_defaults.windows_foundation_uri_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation", "Uri");
  288. il2cpp_defaults.windows_foundation_iuri_runtime_class_class = Class::FromName(windowsRuntimeMetadataImage, "Windows.Foundation", "IUriRuntimeClass");
  289. }
  290. Class::Init(il2cpp_defaults.string_class);
  291. os::Socket::Startup();
  292. #if IL2CPP_MONO_DEBUGGER
  293. il2cpp::utils::Debugger::Init();
  294. #endif
  295. Il2CppDomain* domain = Domain::GetCurrent();
  296. Il2CppThread* mainThread = Thread::Attach(domain);
  297. Thread::SetMain(mainThread);
  298. #if !IL2CPP_TINY
  299. Il2CppAppDomainSetup* setup = (Il2CppAppDomainSetup*)Object::NewPinned(il2cpp_defaults.appdomain_setup_class);
  300. Il2CppAppDomain* ad = (Il2CppAppDomain*)Object::NewPinned(il2cpp_defaults.appdomain_class);
  301. gc::WriteBarrier::GenericStore(&ad->data, domain);
  302. gc::WriteBarrier::GenericStore(&domain->domain, ad);
  303. gc::WriteBarrier::GenericStore(&domain->setup, setup);
  304. #endif
  305. domain->domain_id = 1; // Only have a single domain ATM.
  306. domain->friendly_name = basepath(domainName);
  307. LastError::InitializeLastErrorThreadStatic();
  308. gc::GarbageCollector::InitializeFinalizer();
  309. MetadataCache::InitializeGCSafe();
  310. String::InitializeEmptyString(il2cpp_defaults.string_class);
  311. InitializeStringEmpty();
  312. g_il2cpp_is_fully_initialized = true;
  313. // Force binary serialization in Mono to use reflection instead of code generation.
  314. #undef SetEnvironmentVariable // Get rid of windows.h #define.
  315. os::Environment::SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
  316. os::Environment::SetEnvironmentVariable("MONO_XMLSERIALIZER_THS", "no");
  317. #if !IL2CPP_TINY
  318. Domain::ContextInit(domain);
  319. Domain::ContextSet(domain->default_context);
  320. #endif
  321. VerifyApiVersion();
  322. #if IL2CPP_MONO_DEBUGGER
  323. il2cpp::utils::Debugger::Start();
  324. #endif
  325. std::string executablePath = os::Path::GetExecutablePath();
  326. SetConfigStr(executablePath);
  327. if (utils::Environment::GetNumMainArgs() == 0)
  328. {
  329. // If main args were never set, we default to 1 arg that is the executable path
  330. const char* mainArgs[] = { executablePath.c_str() };
  331. utils::Environment::SetMainArgs(mainArgs, 1);
  332. }
  333. vm::MetadataCache::ExecuteEagerStaticClassConstructors();
  334. vm::MetadataCache::ExecuteModuleInitializers();
  335. hybridclr::Runtime::Initialize();
  336. return true;
  337. }
  338. void Runtime::Shutdown()
  339. {
  340. os::FastAutoLock lock(&s_InitLock);
  341. IL2CPP_ASSERT(s_RuntimeInitCount > 0);
  342. if (--s_RuntimeInitCount > 0)
  343. return;
  344. shutting_down = true;
  345. #if IL2CPP_ENABLE_PROFILER
  346. il2cpp::vm::Profiler::Shutdown();
  347. #endif
  348. #if IL2CPP_MONO_DEBUGGER
  349. // new mono profiler APIs used by debugger
  350. MONO_PROFILER_RAISE(runtime_shutdown_end, ());
  351. #endif
  352. #if IL2CPP_SUPPORT_THREADS
  353. threadpool_ms_cleanup();
  354. #endif
  355. // Tries to abort all threads
  356. // Threads at alertable waits may not have existing when this return
  357. Thread::AbortAllThreads();
  358. os::Socket::Cleanup();
  359. String::CleanupEmptyString();
  360. il2cpp::gc::GarbageCollector::UninitializeFinalizers();
  361. // after the gc cleanup so the finalizer thread can unregister itself
  362. Thread::Uninitialize();
  363. #if IL2CPP_HAS_OS_SYNCHRONIZATION_CONTEXT
  364. // Has to happen before os::Thread::Shutdown() due to it needing a COM apartment on Windows
  365. il2cpp::os::SynchronizationContext::Shutdown();
  366. #endif
  367. os::Thread::Shutdown();
  368. #if IL2CPP_ENABLE_RELOAD
  369. MetadataCache::Clear();
  370. #endif
  371. // We need to do this after thread shut down because it is freeing GC fixed memory
  372. il2cpp::gc::GarbageCollector::UninitializeGC();
  373. // This needs to happen after no managed code can run anymore, including GC finalizers
  374. os::LibraryLoader::CleanupLoadedLibraries();
  375. vm::Image::ClearCachedResourceData();
  376. MetadataAllocCleanup();
  377. vm::COMEntryPoints::FreeCachedData();
  378. os::Locale::UnInitialize();
  379. os::Uninitialize();
  380. Reflection::ClearStatics();
  381. #if IL2CPP_ENABLE_RELOAD
  382. if (g_ClearMethodMetadataInitializedFlags != NULL)
  383. g_ClearMethodMetadataInitializedFlags();
  384. #endif
  385. }
  386. bool Runtime::IsShuttingDown()
  387. {
  388. return shutting_down;
  389. }
  390. void Runtime::SetConfigDir(const char *path)
  391. {
  392. s_ConfigDir = path;
  393. }
  394. static void SetConfigStr(const std::string& executablePath)
  395. {
  396. #if !IL2CPP_TINY
  397. Il2CppDomain* domain = vm::Domain::GetCurrent();
  398. std::string configFileName = utils::PathUtils::Basename(executablePath);
  399. configFileName.append(".config");
  400. std::string appBase = utils::PathUtils::DirectoryName(executablePath);
  401. IL2CPP_OBJECT_SETREF(domain->setup, application_base, vm::String::New(appBase.c_str()));
  402. IL2CPP_OBJECT_SETREF(domain->setup, configuration_file, vm::String::New(configFileName.c_str()));
  403. #endif
  404. }
  405. void Runtime::SetConfigUtf16(const Il2CppChar* executablePath)
  406. {
  407. IL2CPP_ASSERT(executablePath);
  408. std::string exePathUtf8 = il2cpp::utils::StringUtils::Utf16ToUtf8(executablePath);
  409. SetConfigStr(exePathUtf8);
  410. }
  411. void Runtime::SetConfig(const char* executablePath)
  412. {
  413. IL2CPP_ASSERT(executablePath);
  414. std::string executablePathStr(executablePath);
  415. SetConfigStr(executablePathStr);
  416. }
  417. void Runtime::SetUnityTlsInterface(const void* unitytlsInterface)
  418. {
  419. s_UnitytlsInterface = unitytlsInterface;
  420. }
  421. const char *Runtime::GetFrameworkVersion()
  422. {
  423. return s_FrameworkVersion;
  424. }
  425. std::string Runtime::GetConfigDir()
  426. {
  427. if (s_ConfigDir.size() > 0)
  428. return s_ConfigDir;
  429. return utils::PathUtils::Combine(utils::Runtime::GetDataDir(), utils::StringView<char>("etc"));
  430. }
  431. const void* Runtime::GetUnityTlsInterface()
  432. {
  433. return s_UnitytlsInterface;
  434. }
  435. const MethodInfo* Runtime::GetDelegateInvoke(Il2CppClass* klass)
  436. {
  437. const MethodInfo* invoke = Class::GetMethodFromName(klass, "Invoke", -1);
  438. IL2CPP_ASSERT(invoke);
  439. return invoke;
  440. }
  441. Il2CppObject* Runtime::DelegateInvoke(Il2CppDelegate *delegate, void **params, Il2CppException **exc)
  442. {
  443. const MethodInfo* invoke = GetDelegateInvoke(delegate->object.klass);
  444. return Invoke(invoke, delegate, params, exc);
  445. }
  446. void Runtime::GetGenericVirtualMethod(const MethodInfo* vtableSlotMethod, const MethodInfo* genericVirtualMethod, VirtualInvokeData* invokeData)
  447. {
  448. invokeData->method = metadata::GenericMethod::GetGenericVirtualMethod(vtableSlotMethod, genericVirtualMethod);
  449. invokeData->methodPtr = metadata::GenericMethod::GetVirtualCallMethodPointer(invokeData->method);
  450. RaiseExecutionEngineExceptionIfGenericVirtualMethodIsNotFound(invokeData->method, invokeData->method->genericMethod, genericVirtualMethod);
  451. }
  452. Il2CppObject* Runtime::Invoke(const MethodInfo *method, void *obj, void **params, Il2CppException **exc)
  453. {
  454. if (exc)
  455. il2cpp::gc::WriteBarrier::GenericStoreNull(exc);
  456. // we wrap invoker call in try/catch here, rather than emitting a try/catch
  457. // in every invoke call as that blows up the code size.
  458. try
  459. {
  460. if ((method->flags & METHOD_ATTRIBUTE_STATIC) && method->klass && !method->klass->cctor_finished_or_no_cctor)
  461. ClassInit(method->klass);
  462. return InvokeWithThrow(method, obj, params);
  463. }
  464. catch (Il2CppExceptionWrapper& ex)
  465. {
  466. if (exc)
  467. il2cpp::gc::WriteBarrier::GenericStore(exc, ex.ex);
  468. return NULL;
  469. }
  470. }
  471. Il2CppObject* Runtime::InvokeWithThrow(const MethodInfo *method, void *obj, void **params)
  472. {
  473. hybridclr::InitAndGetInterpreterDirectlyCallMethodPointer(method);
  474. if (method->return_type->type == IL2CPP_TYPE_VOID)
  475. {
  476. method->invoker_method(method->methodPointer, method, obj, params, NULL);
  477. return NULL;
  478. }
  479. else
  480. {
  481. if (method->return_type->valuetype)
  482. {
  483. Il2CppClass* returnType = Class::FromIl2CppType(method->return_type);
  484. Class::Init(returnType);
  485. void* returnValue = alloca(returnType->instance_size - sizeof(Il2CppObject));
  486. method->invoker_method(method->methodPointer, method, obj, params, returnValue);
  487. return Object::Box(returnType, returnValue);
  488. }
  489. else
  490. {
  491. // Note that here method->return_type might be a reference type or it might be
  492. // a value type returned by reference.
  493. void* returnValue = NULL;
  494. method->invoker_method(method->methodPointer, method, obj, params, &returnValue);
  495. if (method->return_type->byref)
  496. {
  497. // We cannot use method->return_type->valuetype here, because that will be
  498. // false for methods that return by reference. Instead, get the class for the
  499. // type, which discards the byref flag.
  500. Il2CppClass* returnType = Class::FromIl2CppType(method->return_type);
  501. if (vm::Class::IsValuetype(returnType))
  502. return Object::Box(returnType, returnValue);
  503. return *(Il2CppObject**)returnValue;
  504. }
  505. return (Il2CppObject*)returnValue;
  506. }
  507. }
  508. }
  509. Il2CppObject* Runtime::InvokeArray(const MethodInfo *method, void *obj, Il2CppArray *params, Il2CppException **exc)
  510. {
  511. if (params == NULL)
  512. return InvokeConvertArgs(method, obj, NULL, 0, exc);
  513. // TO DO: when changing GC to one that moves managed objects around, mark params array local variable as pinned!
  514. return InvokeConvertArgs(method, obj, reinterpret_cast<Il2CppObject**>(Array::GetFirstElementAddress(params)), Array::GetLength(params), exc);
  515. }
  516. void Runtime::ObjectInit(Il2CppObject *object)
  517. {
  518. ObjectInitException(object, NULL);
  519. }
  520. void Runtime::ObjectInitException(Il2CppObject *object, Il2CppException **exc)
  521. {
  522. const MethodInfo *method = NULL;
  523. Il2CppClass *klass = object->klass;
  524. method = Class::GetMethodFromName(klass, ".ctor", 0);
  525. IL2CPP_ASSERT(method != NULL && "ObjectInit; no default constructor for object is found");
  526. if (method->klass->byval_arg.valuetype)
  527. object = (Il2CppObject*)Object::Unbox(object);
  528. Invoke(method, object, NULL, exc);
  529. }
  530. void Runtime::SetUnhandledExceptionPolicy(Il2CppRuntimeUnhandledExceptionPolicy value)
  531. {
  532. s_UnhandledExceptionPolicy = value;
  533. }
  534. Il2CppRuntimeUnhandledExceptionPolicy Runtime::GetUnhandledExceptionPolicy()
  535. {
  536. return s_UnhandledExceptionPolicy;
  537. }
  538. void Runtime::UnhandledException(Il2CppException* exc)
  539. {
  540. Il2CppDomain *currentDomain = Domain::GetCurrent();
  541. Il2CppDomain *rootDomain = Domain::GetRoot();
  542. FieldInfo *field;
  543. Il2CppObject *current_appdomain_delegate = NULL;
  544. Il2CppObject *root_appdomain_delegate = NULL;
  545. field = Class::GetFieldFromName(il2cpp_defaults.appdomain_class, "UnhandledException");
  546. IL2CPP_ASSERT(field);
  547. Il2CppObject* excObject = (Il2CppObject*)exc;
  548. if (excObject->klass != il2cpp_defaults.threadabortexception_class)
  549. {
  550. //bool abort_process = (Thread::Current () == Thread::Main ()) ||
  551. // (Runtime::GetUnhandledExceptionPolicy () == IL2CPP_UNHANDLED_POLICY_CURRENT);
  552. Field::GetValue((Il2CppObject*)rootDomain->domain, field, &root_appdomain_delegate);
  553. IL2CPP_NOT_IMPLEMENTED_NO_ASSERT(Runtime::UnhandledException, "We don't have runtime version info yet");
  554. //if (currentDomain != rootDomain && (mono_framework_version () >= 2)) {
  555. // Field::GetValue ((Il2CppObject*)currentDomain->domain, field, &current_appdomain_delegate);
  556. //}
  557. //else
  558. //{
  559. // current_appdomain_delegate = NULL;
  560. //}
  561. ///* set exitcode only if we will abort the process */
  562. //if (abort_process)
  563. // mono_environment_exitcode_set (1);
  564. //if ((current_appdomain_delegate == NULL) && (root_appdomain_delegate == NULL)
  565. //{
  566. // mono_print_unhandled_exception (exc);
  567. //}
  568. //else
  569. {
  570. if (root_appdomain_delegate)
  571. {
  572. CallUnhandledExceptionDelegate(rootDomain, (Il2CppDelegate*)root_appdomain_delegate, exc);
  573. }
  574. if (current_appdomain_delegate)
  575. {
  576. CallUnhandledExceptionDelegate(currentDomain, (Il2CppDelegate*)current_appdomain_delegate, exc);
  577. }
  578. }
  579. }
  580. }
  581. static inline Il2CppObject* InvokeConvertThis(const MethodInfo* method, void* thisArg, void** convertedParameters, Il2CppException** exception)
  582. {
  583. Il2CppClass* thisType = method->klass;
  584. // If it's not a constructor, just invoke directly
  585. if (strcmp(method->name, ".ctor") != 0 || method->klass == il2cpp_defaults.string_class)
  586. {
  587. void* obj = thisArg;
  588. if (Class::IsNullable(method->klass))
  589. {
  590. Il2CppObject* nullable;
  591. /* Convert the unboxed vtype into a Nullable structure */
  592. nullable = Object::New(method->klass);
  593. Il2CppObject* boxed = Object::Box(method->klass->castClass, obj);
  594. Object::NullableInit((uint8_t*)Object::Unbox(nullable), boxed, method->klass);
  595. obj = Object::Unbox(nullable);
  596. }
  597. return Runtime::Invoke(method, obj, convertedParameters, exception);
  598. }
  599. // If it is a construction, we need to construct a return value and allocate object if needed
  600. Il2CppObject* instance;
  601. if (thisArg == NULL)
  602. {
  603. if (Class::IsNullable(thisType))
  604. {
  605. // in the case of a Nullable constructor we can just return a boxed value type
  606. IL2CPP_ASSERT(convertedParameters);
  607. instance = Object::Box(thisType->castClass, convertedParameters[0]);
  608. }
  609. else
  610. {
  611. thisArg = instance = Object::New(thisType);
  612. Runtime::Invoke(method, thisType->byval_arg.valuetype ? Object::Unbox((Il2CppObject*)thisArg) : thisArg, convertedParameters, exception);
  613. }
  614. }
  615. else
  616. {
  617. // thisArg is pointer to data in case of a value type
  618. // We need to invoke the constructor first, passing point to the value
  619. // Since the constructor may modify the value, we need to box the result
  620. // AFTER the constructor was invoked
  621. Runtime::Invoke(method, thisArg, convertedParameters, exception);
  622. instance = Object::Box(thisType, thisArg);
  623. }
  624. return instance;
  625. }
  626. Il2CppObject* Runtime::InvokeConvertArgs(const MethodInfo *method, void* thisArg, Il2CppObject** parameters, int paramCount, Il2CppException** exception)
  627. {
  628. void** convertedParameters = NULL;
  629. bool hasByRefNullables = false;
  630. // Convert parameters if they are not null
  631. if (parameters != NULL)
  632. {
  633. convertedParameters = (void**)alloca(sizeof(void*) * paramCount);
  634. for (int i = 0; i < paramCount; i++)
  635. {
  636. bool passedByReference = method->parameters[i]->byref;
  637. Il2CppClass* parameterType = Class::FromIl2CppType(method->parameters[i]);
  638. Class::Init(parameterType);
  639. if (Class::IsValuetype(parameterType))
  640. {
  641. if (Class::IsNullable(parameterType))
  642. {
  643. // Since we don't really store boxed nullables, we need to create a new one.
  644. void* nullableStorage = alloca(parameterType->instance_size - sizeof(Il2CppObject));
  645. Object::UnboxNullable(parameters[i], parameterType, nullableStorage);
  646. convertedParameters[i] = nullableStorage;
  647. hasByRefNullables |= passedByReference;
  648. }
  649. else if (passedByReference)
  650. {
  651. // If value type is passed by reference, just pass pointer to value directly
  652. // If null was passed in, create a new boxed value type in its place
  653. if (parameters[i] == NULL)
  654. gc::WriteBarrier::GenericStore(parameters + i, Object::New(parameterType));
  655. convertedParameters[i] = Object::Unbox(parameters[i]);
  656. }
  657. else if (parameters[i] == NULL) // If value type is passed by value, we need to pass pointer to its value
  658. {
  659. // If null was passed in, allocate a new value with default value
  660. uint32_t valueSize = parameterType->instance_size - sizeof(Il2CppObject);
  661. convertedParameters[i] = alloca(valueSize);
  662. memset(convertedParameters[i], 0, valueSize);
  663. }
  664. else
  665. {
  666. // Otherwise, pass the original
  667. convertedParameters[i] = Object::Unbox(parameters[i]);
  668. }
  669. }
  670. else if (passedByReference)
  671. {
  672. convertedParameters[i] = &parameters[i]; // Reference type passed by reference
  673. }
  674. else if (parameterType->byval_arg.type == IL2CPP_TYPE_PTR)
  675. {
  676. if (parameters[i] != NULL)
  677. {
  678. IL2CPP_ASSERT(parameters[i]->klass == il2cpp_defaults.int_class);
  679. convertedParameters[i] = reinterpret_cast<void*>(*static_cast<intptr_t*>(Object::Unbox(parameters[i])));
  680. }
  681. else
  682. {
  683. convertedParameters[i] = NULL;
  684. }
  685. }
  686. else
  687. {
  688. convertedParameters[i] = parameters[i]; // Reference type passed by value
  689. }
  690. }
  691. }
  692. Il2CppObject* result = InvokeConvertThis(method, thisArg, convertedParameters, exception);
  693. if (hasByRefNullables)
  694. {
  695. // We need to copy by reference nullables back to original argument array
  696. for (int i = 0; i < paramCount; i++)
  697. {
  698. if (!method->parameters[i]->byref)
  699. continue;
  700. Il2CppClass* parameterType = Class::FromIl2CppType(method->parameters[i]);
  701. if (Class::IsNullable(parameterType))
  702. gc::WriteBarrier::GenericStore(parameters + i, Object::Box(parameterType, convertedParameters[i]));
  703. }
  704. }
  705. if (method->return_type->type == IL2CPP_TYPE_PTR)
  706. {
  707. static Il2CppClass* pointerClass = Class::FromName(il2cpp_defaults.corlib, "System.Reflection", "Pointer");
  708. Il2CppReflectionPointer* pointer = reinterpret_cast<Il2CppReflectionPointer*>(Object::New(pointerClass));
  709. pointer->data = result;
  710. IL2CPP_OBJECT_SETREF(pointer, type, Reflection::GetTypeObject(method->return_type));
  711. result = reinterpret_cast<Il2CppObject*>(pointer);
  712. }
  713. return result;
  714. }
  715. void Runtime::CallUnhandledExceptionDelegate(Il2CppDomain* domain, Il2CppDelegate* delegate, Il2CppException* exc)
  716. {
  717. Il2CppException *e = NULL;
  718. void* pa[2];
  719. pa[0] = domain->domain;
  720. pa[1] = CreateUnhandledExceptionEventArgs(exc);
  721. DelegateInvoke(delegate, pa, &e);
  722. // A managed exception occurred during the unhandled exception handler.
  723. // We can't do much else here other than try to abort the process.
  724. if (e != NULL)
  725. utils::Runtime::Abort();
  726. }
  727. static baselib::ReentrantLock s_TypeInitializationLock;
  728. // We currently call Runtime::ClassInit in 4 places:
  729. // 1. Just after we allocate storage for a new object (Object::NewAllocSpecific)
  730. // 2. Just before reading any static field
  731. // 3. Just before calling any static method
  732. // 4. Just before calling class instance constructor from a derived class instance constructor
  733. void Runtime::ClassInit(Il2CppClass *klass)
  734. {
  735. // Nothing to do if class has no static constructor or already ran.
  736. if (klass->cctor_finished_or_no_cctor)
  737. return;
  738. s_TypeInitializationLock.Acquire();
  739. // See if some thread ran it while we acquired the lock.
  740. if (os::Atomic::CompareExchange(&klass->cctor_finished_or_no_cctor, 1, 1) == 1)
  741. {
  742. s_TypeInitializationLock.Release();
  743. return;
  744. }
  745. // See if some other thread got there first and already started running the constructor.
  746. if (os::Atomic::CompareExchange(&klass->cctor_started, 1, 1) == 1)
  747. {
  748. s_TypeInitializationLock.Release();
  749. // May have been us and we got here through recursion.
  750. os::Thread::ThreadId currentThread = os::Thread::CurrentThreadId();
  751. if (os::Atomic::CompareExchangePointer((size_t**)&klass->cctor_thread, (size_t*)currentThread, (size_t*)currentThread) == (size_t*)currentThread)
  752. return;
  753. // Wait for other thread to finish executing the constructor.
  754. while (os::Atomic::CompareExchange(&klass->cctor_finished_or_no_cctor, 1, 1) != 1 && os::Atomic::CompareExchange(&klass->initializationExceptionGCHandle, 0, 0) == 0)
  755. {
  756. os::Thread::Sleep(1);
  757. }
  758. }
  759. else
  760. {
  761. // Let others know we have started executing the constructor.
  762. os::Atomic::ExchangePointer((size_t**)&klass->cctor_thread, (size_t*)os::Thread::CurrentThreadId());
  763. os::Atomic::Exchange(&klass->cctor_started, 1);
  764. s_TypeInitializationLock.Release();
  765. // Run it.
  766. Il2CppException* exception = NULL;
  767. const MethodInfo* cctor = Class::GetCCtor(klass);
  768. if (cctor != NULL)
  769. {
  770. vm::Runtime::Invoke(cctor, NULL, NULL, &exception);
  771. }
  772. os::Atomic::ExchangePointer((size_t**)&klass->cctor_thread, (size_t*)0);
  773. // Deal with exceptions.
  774. if (exception == NULL)
  775. {
  776. // Let other threads know we finished.
  777. os::Atomic::Exchange(&klass->cctor_finished_or_no_cctor, 1);
  778. }
  779. else
  780. {
  781. const Il2CppType *type = Class::GetType(klass);
  782. 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());
  783. Class::SetClassInitializationError(klass, Exception::GetTypeInitializationException(n.c_str(), exception));
  784. }
  785. }
  786. if (klass->initializationExceptionGCHandle)
  787. {
  788. il2cpp::vm::Exception::Raise((Il2CppException*)gc::GCHandle::GetTarget(klass->initializationExceptionGCHandle));
  789. }
  790. }
  791. struct ConstCharCompare
  792. {
  793. bool operator()(char const *a, char const *b) const
  794. {
  795. return strcmp(a, b) < 0;
  796. }
  797. };
  798. Il2CppObject* Runtime::CreateUnhandledExceptionEventArgs(Il2CppException *exc)
  799. {
  800. Il2CppClass *klass;
  801. void* args[2];
  802. const MethodInfo *method = NULL;
  803. bool is_terminating = true;
  804. Il2CppObject *obj;
  805. klass = Class::FromName(il2cpp_defaults.corlib, "System", "UnhandledExceptionEventArgs");
  806. IL2CPP_ASSERT(klass);
  807. Class::Init(klass);
  808. /* UnhandledExceptionEventArgs only has 1 public ctor with 2 args */
  809. method = Class::GetMethodFromNameFlags(klass, ".ctor", 2, METHOD_ATTRIBUTE_PUBLIC);
  810. IL2CPP_ASSERT(method);
  811. args[0] = exc;
  812. args[1] = &is_terminating;
  813. obj = Object::New(klass);
  814. Runtime::Invoke(method, obj, args, NULL);
  815. return obj;
  816. }
  817. const char *Runtime::GetBundledMachineConfig()
  818. {
  819. return s_BundledMachineConfig;
  820. }
  821. void Runtime::RegisterBundledMachineConfig(const char *config_xml)
  822. {
  823. s_BundledMachineConfig = config_xml;
  824. }
  825. void Runtime::VerifyApiVersion()
  826. {
  827. #if !IL2CPP_TINY
  828. #if IL2CPP_DEBUG
  829. Il2CppClass *klass = Class::FromName(il2cpp_defaults.corlib, "System", "Environment");
  830. Class::Init(klass);
  831. FieldInfo *field = Class::GetFieldFromName(klass, "mono_corlib_version");
  832. Il2CppString* value;
  833. Field::StaticGetValue(field, &value);
  834. std::string version = il2cpp::utils::StringUtils::Utf16ToUtf8(value->chars);
  835. IL2CPP_ASSERT(version == "1A5E0066-58DC-428A-B21C-0AD6CDAE2789");
  836. #endif
  837. #endif
  838. }
  839. int32_t Runtime::GetExitCode()
  840. {
  841. return exitcode;
  842. }
  843. void Runtime::SetExitCode(int32_t value)
  844. {
  845. exitcode = value;
  846. }
  847. static void MissingMethodInvoker(Il2CppMethodPointer ptr, const MethodInfo* method, void* obj, void** args, void* ret)
  848. {
  849. Runtime::RaiseExecutionEngineException(method, false);
  850. }
  851. InvokerMethod Runtime::GetMissingMethodInvoker()
  852. {
  853. return MissingMethodInvoker;
  854. }
  855. void Runtime::AlwaysRaiseExecutionEngineException(const MethodInfo* method)
  856. {
  857. RaiseExecutionEngineException(method, false);
  858. }
  859. void Runtime::AlwaysRaiseExecutionEngineExceptionOnVirtualCall(const MethodInfo* method)
  860. {
  861. RaiseExecutionEngineException(method, true);
  862. }
  863. void Runtime::RaiseExecutionEngineExceptionIfGenericVirtualMethodIsNotFound(const MethodInfo* method, const Il2CppGenericMethod* genericMethod, const MethodInfo* inflatedMethod)
  864. {
  865. if (method->methodPointer == NULL)
  866. {
  867. if (metadata::GenericMethod::IsGenericAmbiguousMethodInfo(method))
  868. {
  869. RaiseAmbiguousImplementationException(inflatedMethod);
  870. }
  871. else
  872. {
  873. RaiseExecutionEngineException(method, metadata::GenericMethod::GetFullName(genericMethod).c_str(), true);
  874. }
  875. }
  876. }
  877. void Runtime::RaiseExecutionEngineException(const MethodInfo* method, bool virtualCall)
  878. {
  879. if (Method::GetClass(method))
  880. RaiseExecutionEngineException(method, Method::GetFullName(method).c_str(), virtualCall);
  881. else
  882. RaiseExecutionEngineException(method, Method::GetNameWithGenericTypes(method).c_str(), virtualCall);
  883. }
  884. void Runtime::RaiseAmbiguousImplementationException(const MethodInfo* method)
  885. {
  886. if (method != NULL && !Method::IsAmbiguousMethodInfo(method))
  887. Exception::Raise(Exception::GetAmbiguousImplementationException(utils::StringUtils::Printf("Attempting to call default interface method for '%s' with ambiguous implementations", Method::GetFullName(method).c_str()).c_str()));
  888. else
  889. Exception::Raise(Exception::GetAmbiguousImplementationException("Attempting to call default interface method with ambiguous implementations"));
  890. }
  891. void Runtime::RaiseExecutionEngineException(const MethodInfo* method, const char* methodFullName, bool virtualCall)
  892. {
  893. if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
  894. {
  895. // Default Interface Method support will throw EntryPointNotFoundExceptions if an abstract interface method is accessed
  896. Exception::Raise(Exception::GetEntryPointNotFoundException(utils::StringUtils::Printf("Attempting to call abstract method '%s'", methodFullName).c_str()));
  897. }
  898. else
  899. {
  900. std::string help = "";
  901. if (virtualCall && (method->flags & METHOD_ATTRIBUTE_VIRTUAL) && method->is_inflated)
  902. help = utils::StringUtils::Printf(" Consider increasing the --generic-virtual-method-iterations=%d argument", metadata::GenericMetadata::GetGenericVirtualIterations());
  903. Exception::Raise(Exception::GetExecutionEngineException(utils::StringUtils::Printf("Attempting to call method '%s' for which no ahead of time (AOT) code was generated.%s", methodFullName, help.c_str()).c_str()));
  904. }
  905. }
  906. #if IL2CPP_TINY
  907. void Runtime::FailFast(const std::string& message)
  908. {
  909. if (!message.empty())
  910. {
  911. il2cpp::utils::Logging::Write(message.c_str());
  912. }
  913. else
  914. {
  915. il2cpp::utils::Logging::Write("No error message was provided. Hopefully the stack trace can provide some information.");
  916. }
  917. const char* managedStackTrace = vm::StackTrace::GetStackTrace();
  918. if (managedStackTrace != NULL && strlen(managedStackTrace) != 0)
  919. {
  920. std::string managedStackTraceMessage = std::string("Managed stack trace:\n") + managedStackTrace;
  921. il2cpp::utils::Logging::Write(managedStackTraceMessage.c_str());
  922. }
  923. else
  924. {
  925. il2cpp::utils::Logging::Write("No managed stack trace exists. Make sure this is a development build to enable managed stack traces.");
  926. }
  927. il2cpp::os::CrashHelpers::Crash();
  928. }
  929. #endif
  930. } /* namespace vm */
  931. } /* namespace il2cpp */