GenericMethod.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. #include "il2cpp-config.h"
  2. #include "metadata/GenericMetadata.h"
  3. #include "metadata/GenericMethod.h"
  4. #include "metadata/GenericSharing.h"
  5. #include "metadata/Il2CppGenericMethodCompare.h"
  6. #include "metadata/Il2CppGenericMethodHash.h"
  7. #include "os/Atomic.h"
  8. #include "os/Mutex.h"
  9. #include "utils/Memory.h"
  10. #include "vm/Class.h"
  11. #include "vm/Exception.h"
  12. #include "vm/GenericClass.h"
  13. #include "vm/MetadataAlloc.h"
  14. #include "vm/MetadataCache.h"
  15. #include "vm/MetadataLock.h"
  16. #include "vm/Method.h"
  17. #include "vm/Runtime.h"
  18. #include "vm/Type.h"
  19. #include "utils/Il2CppHashMap.h"
  20. #include "utils/InitOnce.h"
  21. #include "il2cpp-class-internals.h"
  22. #include "il2cpp-runtime-metadata.h"
  23. #include "il2cpp-runtime-stats.h"
  24. #include <string>
  25. using il2cpp::metadata::GenericMetadata;
  26. using il2cpp::metadata::GenericSharing;
  27. using il2cpp::os::FastAutoLock;
  28. using il2cpp::vm::Class;
  29. using il2cpp::vm::GenericClass;
  30. using il2cpp::vm::MetadataCalloc;
  31. using il2cpp::vm::MetadataCache;
  32. using il2cpp::vm::Method;
  33. using il2cpp::vm::Runtime;
  34. using il2cpp::vm::Type;
  35. struct FullySharedGenericMethodInfo : public MethodInfo
  36. {
  37. FullySharedGenericMethodInfo() { memset(this, 0, sizeof(*this)); }
  38. Il2CppMethodPointer rawVirtualMethodPointer;
  39. Il2CppMethodPointer rawDirectMethodPointer;
  40. InvokerMethod rawInvokerMethod;
  41. };
  42. static size_t SizeOfGenericMethodInfo(bool hasFullGenericSignature)
  43. {
  44. if (hasFullGenericSignature)
  45. return sizeof(FullySharedGenericMethodInfo);
  46. return sizeof(MethodInfo);
  47. }
  48. static MethodInfo* AllocGenericMethodInfo(bool hasFullGenericSignature)
  49. {
  50. return (MethodInfo*)MetadataCalloc(1, SizeOfGenericMethodInfo(hasFullGenericSignature));
  51. }
  52. static MethodInfo* AllocCopyGenericMethodInfo(const MethodInfo* sourceMethodInfo)
  53. {
  54. MethodInfo* newMethodInfo = AllocGenericMethodInfo(sourceMethodInfo->has_full_generic_sharing_signature);
  55. memcpy(newMethodInfo, sourceMethodInfo, SizeOfGenericMethodInfo(sourceMethodInfo->has_full_generic_sharing_signature));
  56. return newMethodInfo;
  57. }
  58. static void FullySharedGenericInvokeRedirectHasAdjustorThunk(Il2CppMethodPointer methodPointer, const MethodInfo* method, void* obj, void** args, void* retVal)
  59. {
  60. IL2CPP_ASSERT(Method::IsGenericInstance(method));
  61. IL2CPP_ASSERT(il2cpp::vm::Runtime::IsFullGenericSharingEnabled());
  62. IL2CPP_ASSERT(methodPointer == method->virtualMethodPointer || methodPointer == method->methodPointer);
  63. const FullySharedGenericMethodInfo* sharedMethodInfo = reinterpret_cast<const FullySharedGenericMethodInfo*>(method);
  64. IL2CPP_ASSERT(sharedMethodInfo->rawDirectMethodPointer != sharedMethodInfo->rawVirtualMethodPointer);
  65. if (methodPointer == sharedMethodInfo->virtualMethodPointer)
  66. sharedMethodInfo->rawInvokerMethod(sharedMethodInfo->rawVirtualMethodPointer, method, obj, args, retVal);
  67. else
  68. sharedMethodInfo->rawInvokerMethod(sharedMethodInfo->rawDirectMethodPointer, method, obj, args, retVal);
  69. }
  70. static void FullySharedGenericInvokeRedirectNoAdjustorThunk(Il2CppMethodPointer methodPointer, const MethodInfo* method, void* obj, void** args, void* retVal)
  71. {
  72. IL2CPP_ASSERT(Method::IsGenericInstance(method));
  73. IL2CPP_ASSERT(il2cpp::vm::Runtime::IsFullGenericSharingEnabled());
  74. IL2CPP_ASSERT(methodPointer == method->methodPointer || methodPointer == method->virtualMethodPointer);
  75. const FullySharedGenericMethodInfo* sharedMethodInfo = reinterpret_cast<const FullySharedGenericMethodInfo*>(method);
  76. IL2CPP_ASSERT(sharedMethodInfo->rawDirectMethodPointer == sharedMethodInfo->rawVirtualMethodPointer);
  77. sharedMethodInfo->rawInvokerMethod(sharedMethodInfo->rawDirectMethodPointer, method, obj, args, retVal);
  78. }
  79. namespace il2cpp
  80. {
  81. namespace metadata
  82. {
  83. typedef Il2CppReaderWriterLockedHashMap<const Il2CppGenericMethod*, MethodInfo*, Il2CppGenericMethodHash, Il2CppGenericMethodCompare> Il2CppGenericMethodMap;
  84. static Il2CppGenericMethodMap s_GenericMethodMap;
  85. static Il2CppGenericMethodMap s_PendingGenericMethodMap;
  86. static bool HasFullGenericSharedParametersOrReturn(const MethodInfo* methodDefinition, const Il2CppType** inflatedParameterTypes)
  87. {
  88. // If a method has a variable sized return type, the FGS method will always
  89. // expect the return value to be passed as a by ref parameter
  90. if (Type::HasVariableRuntimeSizeWhenFullyShared(methodDefinition->return_type))
  91. return true;
  92. for (int i = 0; i < methodDefinition->parameters_count; i++)
  93. {
  94. // Value types are passed by ref, but reference types are passed normally, so if the inflated parameter is a
  95. // reference type, we don't have a signature difference.
  96. if (Type::IsValueType(inflatedParameterTypes[i]) && Type::HasVariableRuntimeSizeWhenFullyShared(methodDefinition->parameters[i]))
  97. return true;
  98. }
  99. return false;
  100. }
  101. static void AnUnresolvedCallStubWasNotFound()
  102. {
  103. vm::Exception::Raise(vm::Exception::GetExecutionEngineException("An unresolved indirect call lookup failed"));
  104. }
  105. // This method must have a different signature than AnUnresolvedCallStubWasNotFound to prevent identical COMDAT folding
  106. // FullySharedGenericInvokeRedirectHasAdjustorThunk relies on this method having a different address
  107. static void AnUnresolvedCallStubWasNotFoundValueType(void* obj)
  108. {
  109. vm::Exception::Raise(vm::Exception::GetExecutionEngineException("An unresolved indirect call to a value type failed"));
  110. }
  111. static void AGenericMethodWhichIsTooDeeplyNestedWasInvoked()
  112. {
  113. vm::Exception::Raise(vm::Exception::GetMaximumNestedGenericsException());
  114. }
  115. static void AGenericMethodWhichIsTooDeeplyNestedWasInvokedInvoker(Il2CppMethodPointer ptr, const MethodInfo* method, void* obj, void** args, void* ret)
  116. {
  117. AGenericMethodWhichIsTooDeeplyNestedWasInvoked();
  118. }
  119. static FullySharedGenericMethodInfo ambiguousMethodInfo;
  120. bool GenericMethod::IsGenericAmbiguousMethodInfo(const MethodInfo* method)
  121. {
  122. return method == &ambiguousMethodInfo;
  123. }
  124. const MethodInfo* GenericMethod::GetGenericVirtualMethod(const MethodInfo* vtableSlotMethod, const MethodInfo* genericVirtualMethod)
  125. {
  126. IL2CPP_NOT_IMPLEMENTED_NO_ASSERT(GetGenericVirtualMethod, "We should only do the following slow method lookup once and then cache on type itself.");
  127. const Il2CppGenericInst* classInst = NULL;
  128. if (vtableSlotMethod->is_inflated)
  129. {
  130. classInst = vtableSlotMethod->genericMethod->context.class_inst;
  131. vtableSlotMethod = vtableSlotMethod->genericMethod->methodDefinition;
  132. }
  133. return metadata::GenericMethod::GetMethod(vtableSlotMethod, classInst, genericVirtualMethod->genericMethod->context.method_inst);
  134. }
  135. const MethodInfo* GenericMethod::GetMethod(const MethodInfo* methodDefinition, const Il2CppGenericInst* classInst, const Il2CppGenericInst* methodInst)
  136. {
  137. Il2CppGenericMethod gmethod = { 0 };
  138. gmethod.methodDefinition = methodDefinition;
  139. gmethod.context.class_inst = classInst;
  140. gmethod.context.method_inst = methodInst;
  141. return GetMethod(gmethod);
  142. }
  143. MethodInfo* GenericMethod::AllocateNewMethodInfo(const MethodInfo* methodDefinition, const Il2CppGenericInst* classInst, const Il2CppGenericInst* methodInst)
  144. {
  145. const MethodInfo* methodInfo = GetMethod(methodDefinition, classInst, methodInst);
  146. return AllocCopyGenericMethodInfo(methodInfo);
  147. }
  148. const MethodInfo* GenericMethod::GetMethod(const Il2CppGenericMethod& gmethod)
  149. {
  150. // This can be NULL only when we have hit the generic recursion depth limit.
  151. if (gmethod.methodDefinition == NULL)
  152. {
  153. MethodInfo* newMethod = AllocGenericMethodInfo(il2cpp::vm::Runtime::IsFullGenericSharingEnabled());
  154. if (il2cpp::vm::Runtime::IsFullGenericSharingEnabled())
  155. {
  156. ((FullySharedGenericMethodInfo*)newMethod)->rawVirtualMethodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked;
  157. ((FullySharedGenericMethodInfo*)newMethod)->rawDirectMethodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked;
  158. ((FullySharedGenericMethodInfo*)newMethod)->rawInvokerMethod = AGenericMethodWhichIsTooDeeplyNestedWasInvokedInvoker;
  159. }
  160. newMethod->methodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked;
  161. newMethod->virtualMethodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked;
  162. newMethod->invoker_method = AGenericMethodWhichIsTooDeeplyNestedWasInvokedInvoker;
  163. return newMethod;
  164. }
  165. // First check for an already constructed generic method using the shared/reader lock
  166. MethodInfo* existingMethod;
  167. if (s_GenericMethodMap.TryGet(&gmethod, &existingMethod))
  168. return existingMethod;
  169. const MethodInfo* methodDefinition = gmethod.methodDefinition;
  170. if (Method::IsAmbiguousMethodInfo(methodDefinition))
  171. {
  172. // is_inflated is used as an initialized check
  173. if (!ambiguousMethodInfo.is_inflated)
  174. {
  175. memcpy(&ambiguousMethodInfo, gmethod.methodDefinition, sizeof(MethodInfo));
  176. ambiguousMethodInfo.is_inflated = true;
  177. ambiguousMethodInfo.rawVirtualMethodPointer = gmethod.methodDefinition->virtualMethodPointer;
  178. ambiguousMethodInfo.rawDirectMethodPointer = gmethod.methodDefinition->methodPointer;
  179. ambiguousMethodInfo.invoker_method = gmethod.methodDefinition->invoker_method;
  180. }
  181. return &ambiguousMethodInfo;
  182. }
  183. return CreateMethodLocked(gmethod);
  184. }
  185. const MethodInfo* GenericMethod::CreateMethodLocked(const Il2CppGenericMethod& gmethod)
  186. {
  187. // We need to inflate a new generic method, take the metadata mutex
  188. // All code below this point can and does assume mutual exclusion
  189. FastAutoLock lock(&il2cpp::vm::g_MetadataLock);
  190. // Recheck the s_GenericMethodMap in case there was a race to add this generic method
  191. MethodInfo* existingMethod;
  192. if (s_GenericMethodMap.TryGet(&gmethod, &existingMethod))
  193. return existingMethod;
  194. // GetMethodLocked may be called recursively, we keep tracking of pending inflations
  195. if (s_PendingGenericMethodMap.TryGet(&gmethod, &existingMethod))
  196. return existingMethod;
  197. const MethodInfo* methodDefinition = gmethod.methodDefinition;
  198. Il2CppClass* declaringClass = methodDefinition->klass;
  199. if (gmethod.context.class_inst)
  200. {
  201. Il2CppGenericClass* genericClassDeclaringType = GenericMetadata::GetGenericClass(methodDefinition->klass, gmethod.context.class_inst);
  202. declaringClass = GenericClass::GetClass(genericClassDeclaringType);
  203. // we may fail if we cannot construct generic type
  204. if (!declaringClass)
  205. return NULL;
  206. }
  207. const Il2CppType** parameters = GenericMetadata::InflateParameters(methodDefinition->parameters, methodDefinition->parameters_count, &gmethod.context, true);
  208. il2cpp::vm::Il2CppGenericMethodPointers methodPointers = MetadataCache::GetGenericMethodPointers(methodDefinition, &gmethod.context);
  209. bool hasFullGenericSharingSignature = methodPointers.isFullGenericShared && HasFullGenericSharedParametersOrReturn(methodDefinition, parameters);
  210. MethodInfo* newMethod = AllocGenericMethodInfo(hasFullGenericSharingSignature);
  211. // we set the pending generic method map here because the initialization may recurse and try to retrieve the same generic method
  212. // this is safe because we *always* take the lock when retrieving the MethodInfo from a generic method.
  213. // if we move lock to only if MethodInfo needs constructed then we need to revisit this since we could return a partially initialized MethodInfo
  214. s_PendingGenericMethodMap.Add(&gmethod, newMethod);
  215. newMethod->klass = declaringClass;
  216. newMethod->flags = methodDefinition->flags;
  217. newMethod->iflags = methodDefinition->iflags;
  218. newMethod->slot = methodDefinition->slot;
  219. newMethod->name = methodDefinition->name;
  220. newMethod->is_generic = false;
  221. newMethod->is_inflated = true;
  222. newMethod->token = methodDefinition->token;
  223. newMethod->return_type = GenericMetadata::InflateIfNeeded(methodDefinition->return_type, &gmethod.context, true);
  224. newMethod->parameters_count = methodDefinition->parameters_count;
  225. newMethod->parameters = parameters;
  226. newMethod->genericMethod = (Il2CppGenericMethod*)MetadataCalloc(1, sizeof(Il2CppGenericMethod));
  227. *const_cast<Il2CppGenericMethod*>(newMethod->genericMethod) = gmethod;
  228. if (!gmethod.context.method_inst)
  229. {
  230. if (methodDefinition->is_generic)
  231. newMethod->is_generic = true;
  232. if (!declaringClass->generic_class)
  233. {
  234. newMethod->genericContainerHandle = methodDefinition->genericContainerHandle;
  235. }
  236. newMethod->methodMetadataHandle = methodDefinition->methodMetadataHandle;
  237. }
  238. else if (!il2cpp::vm::Runtime::IsLazyRGCTXInflationEnabled() && !il2cpp::metadata::GenericMetadata::ContainsGenericParameters(newMethod))
  239. {
  240. // we only need RGCTX for generic instance methods
  241. newMethod->rgctx_data = InflateRGCTXLocked(gmethod, lock);
  242. }
  243. newMethod->virtualMethodPointer = methodPointers.virtualMethodPointer;
  244. newMethod->methodPointer = methodPointers.methodPointer;
  245. if (methodPointers.methodPointer)
  246. {
  247. newMethod->invoker_method = methodPointers.invoker_method;
  248. }
  249. else
  250. {
  251. newMethod->invoker_method = Runtime::GetMissingMethodInvoker();
  252. il2cpp::vm::Il2CppUnresolvedCallStubs stubs = MetadataCache::GetUnresovledCallStubs(newMethod);
  253. newMethod->methodPointer = stubs.methodPointer;
  254. newMethod->virtualMethodPointer = stubs.virtualMethodPointer;
  255. }
  256. newMethod->has_full_generic_sharing_signature = hasFullGenericSharingSignature;
  257. ++il2cpp_runtime_stats.inflated_method_count;
  258. if (il2cpp::vm::Method::HasFullGenericSharingSignature(newMethod))
  259. {
  260. // The method has a full generic sharing signature - that is it a fully shared method an has any fully shared parameter types or return type,
  261. // then its signature doesn't match the expected signature
  262. // e.g. If List<T>::Insert(T t) is fully shared then for List<int>::Insert(int), the C++ fully shared instance would be List::Insert(void*) and require an int* to be passed in.
  263. // So in that case we use the unresolved call stubs to find a matching standard signature to wrap any indirect/virtual calls
  264. FullySharedGenericMethodInfo* sharedMethodInfo = reinterpret_cast<FullySharedGenericMethodInfo*>(newMethod);
  265. sharedMethodInfo->rawVirtualMethodPointer = newMethod->virtualMethodPointer;
  266. sharedMethodInfo->rawDirectMethodPointer = newMethod->methodPointer;
  267. sharedMethodInfo->rawInvokerMethod = newMethod->invoker_method;
  268. bool hasAdjustorThunk = newMethod->methodPointer != newMethod->virtualMethodPointer;
  269. if (hasAdjustorThunk)
  270. newMethod->invoker_method = FullySharedGenericInvokeRedirectHasAdjustorThunk;
  271. else
  272. newMethod->invoker_method = FullySharedGenericInvokeRedirectNoAdjustorThunk;
  273. il2cpp::vm::Il2CppUnresolvedCallStubs stubs = MetadataCache::GetUnresovledCallStubs(newMethod);
  274. if (stubs.stubsFound)
  275. {
  276. newMethod->methodPointer = stubs.methodPointer;
  277. newMethod->virtualMethodPointer = stubs.virtualMethodPointer;
  278. }
  279. else
  280. {
  281. newMethod->methodPointer = AnUnresolvedCallStubWasNotFound;
  282. newMethod->virtualMethodPointer = AnUnresolvedCallStubWasNotFound;
  283. if (hasAdjustorThunk)
  284. {
  285. // The FullySharedGenericInvokeRedirectHasAdjustorThunk requires that methodPointer and virtualMethodPointer be different
  286. // so it can tell which raw* method it should call even though it doesn't directly call them
  287. IL2CPP_ASSERT(reinterpret_cast<Il2CppMethodPointer>(AnUnresolvedCallStubWasNotFoundValueType) != AnUnresolvedCallStubWasNotFound);
  288. if (reinterpret_cast<Il2CppMethodPointer>(AnUnresolvedCallStubWasNotFoundValueType) != AnUnresolvedCallStubWasNotFound)
  289. {
  290. newMethod->methodPointer = reinterpret_cast<Il2CppMethodPointer>(AnUnresolvedCallStubWasNotFoundValueType);
  291. }
  292. else
  293. {
  294. // If we got hit by COMDAT folding (but in DEBUG, which is the most likely way it would happen)
  295. // Ensure that are methodPointers are definitely different
  296. // We'll get an less specific error message, but it's better than corruption
  297. // Make the change on methodPointer because we're most likely to be called
  298. newMethod->methodPointer = il2cpp::vm::Method::GetEntryPointNotFoundMethodInfo()->methodPointer;
  299. }
  300. }
  301. }
  302. }
  303. // If we are a default interface method on a generic instance interface we need to ensure that the interfaces rgctx is inflated
  304. if (Method::IsDefaultInterfaceMethodOnGenericInstance(newMethod))
  305. vm::Class::InitLocked(declaringClass, lock);
  306. // The generic method is fully created,
  307. // Update the generic method map, this needs to take an exclusive lock
  308. // **** This must happen with the metadata lock held and be released before the metadata lock is released ****
  309. // **** This prevents deadlocks and ensures that there is no race condition
  310. // **** creating a new method adding it to s_GenericMethodMap and removing it from s_PendingGenericMethodMap
  311. s_GenericMethodMap.Add(newMethod->genericMethod, newMethod);
  312. // Remove the method from the pending table
  313. s_PendingGenericMethodMap.Remove(&gmethod);
  314. return newMethod;
  315. }
  316. const Il2CppRGCTXData* GenericMethod::InflateRGCTX(const MethodInfo* method)
  317. {
  318. IL2CPP_ASSERT(method->is_inflated);
  319. IL2CPP_ASSERT(method->genericMethod);
  320. IL2CPP_ASSERT(method->genericMethod->context.method_inst);
  321. return il2cpp::utils::InitOnce(const_cast<Il2CppRGCTXData**>(&method->rgctx_data), &il2cpp::vm::g_MetadataLock, [method](const il2cpp::os::FastAutoLock& lock) {
  322. return const_cast<Il2CppRGCTXData*>(GenericMethod::InflateRGCTXLocked(*method->genericMethod, lock));
  323. });
  324. }
  325. const Il2CppRGCTXData* GenericMethod::InflateRGCTXLocked(const Il2CppGenericMethod& gmethod, const il2cpp::os::FastAutoLock &lock)
  326. {
  327. const MethodInfo* methodDefinition = gmethod.methodDefinition;
  328. return GenericMetadata::InflateRGCTXLocked(methodDefinition->klass->image, methodDefinition->token, &gmethod.context, lock);
  329. }
  330. const Il2CppGenericContext* GenericMethod::GetContext(const Il2CppGenericMethod* gmethod)
  331. {
  332. return &gmethod->context;
  333. }
  334. static std::string FormatGenericArguments(const Il2CppGenericInst* inst)
  335. {
  336. std::string output;
  337. if (inst)
  338. {
  339. output.append("<");
  340. for (size_t i = 0; i < inst->type_argc; ++i)
  341. {
  342. if (i != 0)
  343. output.append(", ");
  344. output.append(Type::GetName(inst->type_argv[i], IL2CPP_TYPE_NAME_FORMAT_FULL_NAME));
  345. }
  346. output.append(">");
  347. }
  348. return output;
  349. }
  350. std::string GenericMethod::GetFullName(const Il2CppGenericMethod* gmethod)
  351. {
  352. const MethodInfo* methodDefinition = gmethod->methodDefinition;
  353. std::string output;
  354. output.append(Type::GetName(Class::GetType(Method::GetClass(methodDefinition)), IL2CPP_TYPE_NAME_FORMAT_FULL_NAME));
  355. output.append(FormatGenericArguments(gmethod->context.class_inst));
  356. output.append("::");
  357. output.append(Method::GetName(methodDefinition));
  358. output.append(FormatGenericArguments(gmethod->context.method_inst));
  359. return output;
  360. }
  361. void GenericMethod::ClearStatics()
  362. {
  363. s_GenericMethodMap.Clear();
  364. }
  365. void GenericMethod::AcquireMetadataLocks()
  366. {
  367. s_GenericMethodMap.LockExclusive();
  368. }
  369. void GenericMethod::ReleaseMetadataLocks()
  370. {
  371. s_GenericMethodMap.ReleaseExclusive();
  372. }
  373. } /* namespace vm */
  374. } /* namespace il2cpp */