GenericMethod.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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, true);
  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. return GetMethod(gmethod, false);
  151. }
  152. const MethodInfo* GenericMethod::GetMethod(const Il2CppGenericMethod* gmethod, bool copyMethodPtr)
  153. {
  154. // This can be NULL only when we have hit the generic recursion depth limit.
  155. if (gmethod == NULL)
  156. {
  157. MethodInfo* newMethod = AllocGenericMethodInfo(il2cpp::vm::Runtime::IsFullGenericSharingEnabled());
  158. if (il2cpp::vm::Runtime::IsFullGenericSharingEnabled())
  159. {
  160. ((FullySharedGenericMethodInfo*)newMethod)->rawVirtualMethodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked;
  161. ((FullySharedGenericMethodInfo*)newMethod)->rawDirectMethodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked;
  162. ((FullySharedGenericMethodInfo*)newMethod)->rawInvokerMethod = AGenericMethodWhichIsTooDeeplyNestedWasInvokedInvoker;
  163. }
  164. newMethod->methodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked;
  165. newMethod->virtualMethodPointer = AGenericMethodWhichIsTooDeeplyNestedWasInvoked;
  166. newMethod->invoker_method = AGenericMethodWhichIsTooDeeplyNestedWasInvokedInvoker;
  167. return newMethod;
  168. }
  169. // First check for an already constructed generic method using the shared/reader lock
  170. MethodInfo* existingMethod;
  171. if (s_GenericMethodMap.TryGet(gmethod, &existingMethod))
  172. return existingMethod;
  173. if (Method::IsAmbiguousMethodInfo(gmethod->methodDefinition))
  174. {
  175. // is_inflated is used as an initialized check
  176. if (!ambiguousMethodInfo.is_inflated)
  177. {
  178. memcpy(&ambiguousMethodInfo, gmethod->methodDefinition, sizeof(MethodInfo));
  179. ambiguousMethodInfo.is_inflated = true;
  180. ambiguousMethodInfo.rawVirtualMethodPointer = gmethod->methodDefinition->virtualMethodPointer;
  181. ambiguousMethodInfo.rawDirectMethodPointer = gmethod->methodDefinition->methodPointer;
  182. ambiguousMethodInfo.invoker_method = gmethod->methodDefinition->invoker_method;
  183. }
  184. return &ambiguousMethodInfo;
  185. }
  186. return CreateMethodLocked(gmethod, copyMethodPtr);
  187. }
  188. const MethodInfo* GenericMethod::CreateMethodLocked(const Il2CppGenericMethod* gmethod, bool copyMethodPtr)
  189. {
  190. // We need to inflate a new generic method, take the metadata mutex
  191. // All code below this point can and does assume mutual exclusion
  192. FastAutoLock lock(&il2cpp::vm::g_MetadataLock);
  193. // Recheck the s_GenericMethodMap in case there was a race to add this generic method
  194. MethodInfo* existingMethod;
  195. if (s_GenericMethodMap.TryGet(gmethod, &existingMethod))
  196. return existingMethod;
  197. // GetMethodLocked may be called recursively, we keep tracking of pending inflations
  198. if (s_PendingGenericMethodMap.TryGet(gmethod, &existingMethod))
  199. return existingMethod;
  200. if (copyMethodPtr)
  201. gmethod = MetadataCache::GetGenericMethod(gmethod->methodDefinition, gmethod->context.class_inst, gmethod->context.method_inst);
  202. const MethodInfo* methodDefinition = gmethod->methodDefinition;
  203. Il2CppClass* declaringClass = methodDefinition->klass;
  204. if (gmethod->context.class_inst)
  205. {
  206. Il2CppGenericClass* genericClassDeclaringType = GenericMetadata::GetGenericClass(methodDefinition->klass, gmethod->context.class_inst);
  207. declaringClass = GenericClass::GetClass(genericClassDeclaringType);
  208. // we may fail if we cannot construct generic type
  209. if (!declaringClass)
  210. return NULL;
  211. }
  212. const Il2CppType** parameters = GenericMetadata::InflateParameters(methodDefinition->parameters, methodDefinition->parameters_count, &gmethod->context, true);
  213. il2cpp::vm::Il2CppGenericMethodPointers methodPointers = MetadataCache::GetGenericMethodPointers(methodDefinition, &gmethod->context);
  214. bool hasFullGenericSharingSignature = methodPointers.isFullGenericShared && HasFullGenericSharedParametersOrReturn(gmethod->methodDefinition, parameters);
  215. MethodInfo* newMethod = AllocGenericMethodInfo(hasFullGenericSharingSignature);
  216. // we set the pending generic method map here because the initialization may recurse and try to retrieve the same generic method
  217. // this is safe because we *always* take the lock when retrieving the MethodInfo from a generic method.
  218. // if we move lock to only if MethodInfo needs constructed then we need to revisit this since we could return a partially initialized MethodInfo
  219. s_PendingGenericMethodMap.Add(gmethod, newMethod);
  220. newMethod->klass = declaringClass;
  221. newMethod->flags = methodDefinition->flags;
  222. newMethod->iflags = methodDefinition->iflags;
  223. newMethod->slot = methodDefinition->slot;
  224. newMethod->name = methodDefinition->name;
  225. newMethod->is_generic = false;
  226. newMethod->is_inflated = true;
  227. newMethod->token = methodDefinition->token;
  228. newMethod->return_type = GenericMetadata::InflateIfNeeded(methodDefinition->return_type, &gmethod->context, true);
  229. newMethod->parameters_count = methodDefinition->parameters_count;
  230. newMethod->parameters = parameters;
  231. newMethod->genericMethod = gmethod;
  232. if (!gmethod->context.method_inst)
  233. {
  234. if (methodDefinition->is_generic)
  235. newMethod->is_generic = true;
  236. if (!declaringClass->generic_class)
  237. {
  238. newMethod->genericContainerHandle = methodDefinition->genericContainerHandle;
  239. }
  240. newMethod->methodMetadataHandle = methodDefinition->methodMetadataHandle;
  241. }
  242. else if (!il2cpp::vm::Runtime::IsLazyRGCTXInflationEnabled() && !il2cpp::metadata::GenericMetadata::ContainsGenericParameters(newMethod))
  243. {
  244. // we only need RGCTX for generic instance methods
  245. newMethod->rgctx_data = InflateRGCTXLocked(gmethod, lock);
  246. }
  247. newMethod->virtualMethodPointer = methodPointers.virtualMethodPointer;
  248. newMethod->methodPointer = methodPointers.methodPointer;
  249. if (methodPointers.methodPointer)
  250. {
  251. newMethod->invoker_method = methodPointers.invoker_method;
  252. }
  253. else
  254. {
  255. newMethod->invoker_method = Runtime::GetMissingMethodInvoker();
  256. il2cpp::vm::Il2CppUnresolvedCallStubs stubs = MetadataCache::GetUnresovledCallStubs(newMethod);
  257. newMethod->methodPointer = stubs.methodPointer;
  258. newMethod->virtualMethodPointer = stubs.virtualMethodPointer;
  259. }
  260. newMethod->has_full_generic_sharing_signature = hasFullGenericSharingSignature;
  261. ++il2cpp_runtime_stats.inflated_method_count;
  262. if (il2cpp::vm::Method::HasFullGenericSharingSignature(newMethod))
  263. {
  264. // 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,
  265. // then its signature doesn't match the expected signature
  266. // 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.
  267. // So in that case we use the unresolved call stubs to find a matching standard signature to wrap any indirect/virtual calls
  268. FullySharedGenericMethodInfo* sharedMethodInfo = reinterpret_cast<FullySharedGenericMethodInfo*>(newMethod);
  269. sharedMethodInfo->rawVirtualMethodPointer = newMethod->virtualMethodPointer;
  270. sharedMethodInfo->rawDirectMethodPointer = newMethod->methodPointer;
  271. sharedMethodInfo->rawInvokerMethod = newMethod->invoker_method;
  272. bool hasAdjustorThunk = newMethod->methodPointer != newMethod->virtualMethodPointer;
  273. if (hasAdjustorThunk)
  274. newMethod->invoker_method = FullySharedGenericInvokeRedirectHasAdjustorThunk;
  275. else
  276. newMethod->invoker_method = FullySharedGenericInvokeRedirectNoAdjustorThunk;
  277. il2cpp::vm::Il2CppUnresolvedCallStubs stubs = MetadataCache::GetUnresovledCallStubs(newMethod);
  278. if (stubs.stubsFound)
  279. {
  280. newMethod->methodPointer = stubs.methodPointer;
  281. newMethod->virtualMethodPointer = stubs.virtualMethodPointer;
  282. }
  283. else
  284. {
  285. newMethod->methodPointer = AnUnresolvedCallStubWasNotFound;
  286. newMethod->virtualMethodPointer = AnUnresolvedCallStubWasNotFound;
  287. if (hasAdjustorThunk)
  288. {
  289. // The FullySharedGenericInvokeRedirectHasAdjustorThunk requires that methodPointer and virtualMethodPointer be different
  290. // so it can tell which raw* method it should call even though it doesn't directly call them
  291. IL2CPP_ASSERT(reinterpret_cast<Il2CppMethodPointer>(AnUnresolvedCallStubWasNotFoundValueType) != AnUnresolvedCallStubWasNotFound);
  292. if (reinterpret_cast<Il2CppMethodPointer>(AnUnresolvedCallStubWasNotFoundValueType) != AnUnresolvedCallStubWasNotFound)
  293. {
  294. newMethod->methodPointer = reinterpret_cast<Il2CppMethodPointer>(AnUnresolvedCallStubWasNotFoundValueType);
  295. }
  296. else
  297. {
  298. // If we got hit by COMDAT folding (but in DEBUG, which is the most likely way it would happen)
  299. // Ensure that are methodPointers are definitely different
  300. // We'll get an less specific error message, but it's better than corruption
  301. // Make the change on methodPointer because we're most likely to be called
  302. newMethod->methodPointer = il2cpp::vm::Method::GetEntryPointNotFoundMethodInfo()->methodPointer;
  303. }
  304. }
  305. }
  306. }
  307. // If we are a default interface method on a generic instance interface we need to ensure that the interfaces rgctx is inflated
  308. if (Method::IsDefaultInterfaceMethodOnGenericInstance(newMethod))
  309. vm::Class::InitLocked(declaringClass, lock);
  310. // The generic method is fully created,
  311. // Update the generic method map, this needs to take an exclusive lock
  312. // **** This must happen with the metadata lock held and be released before the metalock is released ****
  313. // **** This prevents deadlocks and ensures that there is no race condition
  314. // **** creating a new method adding it to s_GenericMethodMap and removing it from s_PendingGenericMethodMap
  315. s_GenericMethodMap.Add(gmethod, newMethod);
  316. // Remove the method from the pending table
  317. s_PendingGenericMethodMap.Remove(gmethod);
  318. return newMethod;
  319. }
  320. const Il2CppRGCTXData* GenericMethod::InflateRGCTX(const MethodInfo* method)
  321. {
  322. IL2CPP_ASSERT(method->is_inflated);
  323. IL2CPP_ASSERT(method->genericMethod);
  324. IL2CPP_ASSERT(method->genericMethod->context.method_inst);
  325. return il2cpp::utils::InitOnce(const_cast<Il2CppRGCTXData**>(&method->rgctx_data), &il2cpp::vm::g_MetadataLock, [method](const il2cpp::os::FastAutoLock& lock) {
  326. return const_cast<Il2CppRGCTXData*>(GenericMethod::InflateRGCTXLocked(method->genericMethod, lock));
  327. });
  328. }
  329. const Il2CppRGCTXData* GenericMethod::InflateRGCTXLocked(const Il2CppGenericMethod* gmethod, const il2cpp::os::FastAutoLock &lock)
  330. {
  331. return GenericMetadata::InflateRGCTXLocked(gmethod->methodDefinition->klass->image, gmethod->methodDefinition->token, &gmethod->context, lock);
  332. }
  333. const Il2CppGenericContext* GenericMethod::GetContext(const Il2CppGenericMethod* gmethod)
  334. {
  335. return &gmethod->context;
  336. }
  337. static std::string FormatGenericArguments(const Il2CppGenericInst* inst)
  338. {
  339. std::string output;
  340. if (inst)
  341. {
  342. output.append("<");
  343. for (size_t i = 0; i < inst->type_argc; ++i)
  344. {
  345. if (i != 0)
  346. output.append(", ");
  347. output.append(Type::GetName(inst->type_argv[i], IL2CPP_TYPE_NAME_FORMAT_FULL_NAME));
  348. }
  349. output.append(">");
  350. }
  351. return output;
  352. }
  353. std::string GenericMethod::GetFullName(const Il2CppGenericMethod* gmethod)
  354. {
  355. const MethodInfo* method = gmethod->methodDefinition;
  356. std::string output;
  357. output.append(Type::GetName(&gmethod->methodDefinition->klass->byval_arg, IL2CPP_TYPE_NAME_FORMAT_FULL_NAME));
  358. output.append(FormatGenericArguments(gmethod->context.class_inst));
  359. output.append("::");
  360. output.append(Method::GetName(method));
  361. output.append(FormatGenericArguments(gmethod->context.method_inst));
  362. return output;
  363. }
  364. void GenericMethod::ClearStatics()
  365. {
  366. s_GenericMethodMap.Clear();
  367. }
  368. } /* namespace vm */
  369. } /* namespace il2cpp */