Generator.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. using dnlib.DotNet;
  2. using HybridCLR.Editor.ABI;
  3. using HybridCLR.Editor.Meta;
  4. using HybridCLR.Editor.Template;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel.DataAnnotations;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using UnityEditor;
  14. using UnityEngine;
  15. using TypeInfo = HybridCLR.Editor.ABI.TypeInfo;
  16. using CallingConvention = System.Runtime.InteropServices.CallingConvention;
  17. using TypeAttributes = dnlib.DotNet.TypeAttributes;
  18. using System.Runtime.InteropServices;
  19. namespace HybridCLR.Editor.MethodBridge
  20. {
  21. public class Generator
  22. {
  23. public class Options
  24. {
  25. public string TemplateCode { get; set; }
  26. public string OutputFile { get; set; }
  27. public IReadOnlyCollection<GenericMethod> GenericMethods { get; set; }
  28. public List<RawMonoPInvokeCallbackMethodInfo> ReversePInvokeMethods { get; set; }
  29. public IReadOnlyCollection<CallNativeMethodSignatureInfo> CalliMethodSignatures { get; set; }
  30. public bool Development { get; set; }
  31. }
  32. private class ABIReversePInvokeMethodInfo
  33. {
  34. public MethodDesc Method { get; set; }
  35. public CallingConvention Callvention { get; set; }
  36. public int Count { get; set; }
  37. public string Signature { get; set; }
  38. }
  39. private class CalliMethodInfo
  40. {
  41. public MethodDesc Method { get; set; }
  42. public CallingConvention Callvention { get; set; }
  43. public string Signature { get; set; }
  44. }
  45. private readonly List<GenericMethod> _genericMethods;
  46. private readonly List<RawMonoPInvokeCallbackMethodInfo> _originalReversePInvokeMethods;
  47. private readonly List<CallNativeMethodSignatureInfo> _originalCalliMethodSignatures;
  48. private readonly string _templateCode;
  49. private readonly string _outputFile;
  50. private readonly bool _development;
  51. private readonly TypeCreator _typeCreator;
  52. private readonly HashSet<MethodDesc> _managed2nativeMethodSet = new HashSet<MethodDesc>();
  53. private readonly HashSet<MethodDesc> _native2managedMethodSet = new HashSet<MethodDesc>();
  54. private readonly HashSet<MethodDesc> _adjustThunkMethodSet = new HashSet<MethodDesc>();
  55. private List<ABIReversePInvokeMethodInfo> _reversePInvokeMethods;
  56. private List<CalliMethodInfo> _callidMethods;
  57. public Generator(Options options)
  58. {
  59. List<(GenericMethod, string)> genericMethodInfo = options.GenericMethods.Select(m => (m, m.ToString())).ToList();
  60. genericMethodInfo.Sort((a, b) => string.CompareOrdinal(a.Item2, b.Item2));
  61. _genericMethods = genericMethodInfo.Select(m => m.Item1).ToList();
  62. _originalReversePInvokeMethods = options.ReversePInvokeMethods;
  63. _originalCalliMethodSignatures = options.CalliMethodSignatures.ToList();
  64. _templateCode = options.TemplateCode;
  65. _outputFile = options.OutputFile;
  66. _typeCreator = new TypeCreator();
  67. _development = options.Development;
  68. }
  69. private readonly Dictionary<string, TypeInfo> _sig2Types = new Dictionary<string, TypeInfo>();
  70. private TypeInfo GetSharedTypeInfo(TypeSig type)
  71. {
  72. var typeInfo = _typeCreator.CreateTypeInfo(type);
  73. if (!typeInfo.IsStruct)
  74. {
  75. return typeInfo;
  76. }
  77. string sigName = ToFullName(typeInfo.Klass);
  78. if (!_sig2Types.TryGetValue(sigName, out var sharedTypeInfo))
  79. {
  80. sharedTypeInfo = typeInfo;
  81. _sig2Types.Add(sigName, sharedTypeInfo);
  82. }
  83. return sharedTypeInfo;
  84. }
  85. private MethodDesc CreateMethodDesc(MethodDef methodDef, bool forceRemoveThis, TypeSig returnType, List<TypeSig> parameters)
  86. {
  87. var paramInfos = new List<ParamInfo>();
  88. if (forceRemoveThis && !methodDef.IsStatic)
  89. {
  90. parameters.RemoveAt(0);
  91. }
  92. if (returnType.ContainsGenericParameter)
  93. {
  94. throw new Exception($"[PreservedMethod] method:{methodDef} has generic parameters");
  95. }
  96. foreach (var paramInfo in parameters)
  97. {
  98. if (paramInfo.ContainsGenericParameter)
  99. {
  100. throw new Exception($"[PreservedMethod] method:{methodDef} has generic parameters");
  101. }
  102. paramInfos.Add(new ParamInfo() { Type = GetSharedTypeInfo(paramInfo) });
  103. }
  104. var mbs = new MethodDesc()
  105. {
  106. MethodDef = methodDef,
  107. ReturnInfo = new ReturnInfo() { Type = returnType != null ? GetSharedTypeInfo(returnType) : TypeInfo.s_void },
  108. ParamInfos = paramInfos,
  109. };
  110. return mbs;
  111. }
  112. private MethodDesc CreateMethodDesc(TypeSig returnType, List<TypeSig> parameters)
  113. {
  114. var paramInfos = new List<ParamInfo>();
  115. if (returnType.ContainsGenericParameter)
  116. {
  117. throw new Exception($"[PreservedMethod] method has generic parameters");
  118. }
  119. foreach (var paramInfo in parameters)
  120. {
  121. if (paramInfo.ContainsGenericParameter)
  122. {
  123. throw new Exception($"[PreservedMethod] method has generic parameters");
  124. }
  125. paramInfos.Add(new ParamInfo() { Type = GetSharedTypeInfo(paramInfo) });
  126. }
  127. var mbs = new MethodDesc()
  128. {
  129. MethodDef = null,
  130. ReturnInfo = new ReturnInfo() { Type = returnType != null ? GetSharedTypeInfo(returnType) : TypeInfo.s_void },
  131. ParamInfos = paramInfos,
  132. };
  133. return mbs;
  134. }
  135. private void AddManaged2NativeMethod(MethodDesc method)
  136. {
  137. method.Init();
  138. _managed2nativeMethodSet.Add(method);
  139. }
  140. private void AddNative2ManagedMethod(MethodDesc method)
  141. {
  142. method.Init();
  143. _native2managedMethodSet.Add(method);
  144. }
  145. private void AddAdjustThunkMethod(MethodDesc method)
  146. {
  147. method.Init();
  148. _adjustThunkMethodSet.Add(method);
  149. }
  150. private void ProcessMethod(MethodDef method, List<TypeSig> klassInst, List<TypeSig> methodInst)
  151. {
  152. if (method.IsPrivate || (method.IsAssembly && !method.IsPublic && !method.IsFamily))
  153. {
  154. if (klassInst == null && methodInst == null)
  155. {
  156. return;
  157. }
  158. else
  159. {
  160. //Debug.Log($"[PreservedMethod] method:{method}");
  161. }
  162. }
  163. ICorLibTypes corLibTypes = method.Module.CorLibTypes;
  164. TypeSig returnType;
  165. List<TypeSig> parameters;
  166. if (klassInst == null && methodInst == null)
  167. {
  168. if (method.HasGenericParameters)
  169. {
  170. throw new Exception($"[PreservedMethod] method:{method} has generic parameters");
  171. }
  172. returnType = MetaUtil.ToShareTypeSig(corLibTypes, method.ReturnType);
  173. parameters = method.Parameters.Select(p => MetaUtil.ToShareTypeSig(corLibTypes, p.Type)).ToList();
  174. }
  175. else
  176. {
  177. var gc = new GenericArgumentContext(klassInst, methodInst);
  178. returnType = MetaUtil.ToShareTypeSig(corLibTypes, MetaUtil.Inflate(method.ReturnType, gc));
  179. parameters = method.Parameters.Select(p => MetaUtil.ToShareTypeSig(corLibTypes, MetaUtil.Inflate(p.Type, gc))).ToList();
  180. }
  181. var m2nMethod = CreateMethodDesc(method, false, returnType, parameters);
  182. AddManaged2NativeMethod(m2nMethod);
  183. if (method.IsVirtual)
  184. {
  185. if (method.DeclaringType.IsInterface)
  186. {
  187. AddAdjustThunkMethod(m2nMethod);
  188. }
  189. //var adjustThunkMethod = CreateMethodDesc(method, true, returnType, parameters);
  190. AddNative2ManagedMethod(m2nMethod);
  191. }
  192. if (method.Name == "Invoke" && method.DeclaringType.IsDelegate)
  193. {
  194. var openMethod = CreateMethodDesc(method, true, returnType, parameters);
  195. AddNative2ManagedMethod(openMethod);
  196. }
  197. }
  198. private void PrepareMethodBridges()
  199. {
  200. foreach (var method in _genericMethods)
  201. {
  202. ProcessMethod(method.Method, method.KlassInst, method.MethodInst);
  203. }
  204. foreach (var reversePInvokeMethod in _originalReversePInvokeMethods)
  205. {
  206. MethodDef method = reversePInvokeMethod.Method;
  207. ICorLibTypes corLibTypes = method.Module.CorLibTypes;
  208. var returnType = MetaUtil.ToShareTypeSig(corLibTypes, method.ReturnType);
  209. var parameters = method.Parameters.Select(p => MetaUtil.ToShareTypeSig(corLibTypes, p.Type)).ToList();
  210. var sharedMethod = CreateMethodDesc(method, true, returnType, parameters);
  211. sharedMethod.Init();
  212. AddNative2ManagedMethod(sharedMethod);
  213. }
  214. }
  215. static void CheckUnique(IEnumerable<string> names)
  216. {
  217. var set = new HashSet<string>();
  218. foreach (var name in names)
  219. {
  220. if (!set.Add(name))
  221. {
  222. throw new Exception($"[CheckUnique] duplicate name:{name}");
  223. }
  224. }
  225. }
  226. private List<MethodDesc> _managed2NativeMethodList0;
  227. private List<MethodDesc> _native2ManagedMethodList0;
  228. private List<MethodDesc> _adjustThunkMethodList0;
  229. private List<TypeInfo> _structTypes0;
  230. private void CollectTypesAndMethods()
  231. {
  232. _managed2NativeMethodList0 = _managed2nativeMethodSet.ToList();
  233. _managed2NativeMethodList0.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
  234. _native2ManagedMethodList0 = _native2managedMethodSet.ToList();
  235. _native2ManagedMethodList0.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
  236. _adjustThunkMethodList0 = _adjustThunkMethodSet.ToList();
  237. _adjustThunkMethodList0.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
  238. var structTypeSet = new HashSet<TypeInfo>();
  239. CollectStructDefs(_managed2NativeMethodList0, structTypeSet);
  240. CollectStructDefs(_native2ManagedMethodList0, structTypeSet);
  241. CollectStructDefs(_adjustThunkMethodList0, structTypeSet);
  242. CollectStructDefs(_originalCalliMethodSignatures.Select(m => m.MethodSig).ToList(), structTypeSet);
  243. _structTypes0 = structTypeSet.ToList();
  244. _structTypes0.Sort((a, b) => a.TypeId - b.TypeId);
  245. CheckUnique(_structTypes0.Select(t => ToFullName(t.Klass)));
  246. CheckUnique(_structTypes0.Select(t => t.CreateSigName()));
  247. Debug.LogFormat("== before optimization struct:{3} managed2native:{0} native2managed:{1} adjustThunk:{2}",
  248. _managed2NativeMethodList0.Count, _native2ManagedMethodList0.Count, _adjustThunkMethodList0.Count, _structTypes0.Count);
  249. }
  250. private class AnalyzeFieldInfo
  251. {
  252. public FieldDef field;
  253. public TypeInfo type;
  254. }
  255. private class AnalyzeTypeInfo
  256. {
  257. public TypeInfo isoType;
  258. public List<AnalyzeFieldInfo> fields;
  259. public string signature;
  260. public uint originalPackingSize;
  261. public uint packingSize;
  262. public uint classSize;
  263. public LayoutKind layout;
  264. public bool blittable;
  265. }
  266. private readonly Dictionary<TypeInfo, AnalyzeTypeInfo> _analyzeTypeInfos = new Dictionary<TypeInfo, AnalyzeTypeInfo>();
  267. private readonly Dictionary<string, TypeInfo> _signature2Type = new Dictionary<string, TypeInfo>();
  268. private bool IsBlittable(TypeSig typeSig)
  269. {
  270. typeSig = typeSig.RemovePinnedAndModifiers();
  271. if (typeSig.IsByRef)
  272. {
  273. return true;
  274. }
  275. switch (typeSig.ElementType)
  276. {
  277. case ElementType.Void: return false;
  278. case ElementType.Boolean:
  279. case ElementType.I1:
  280. case ElementType.U1:
  281. case ElementType.I2:
  282. case ElementType.Char:
  283. case ElementType.U2:
  284. case ElementType.I4:
  285. case ElementType.U4:
  286. case ElementType.I8:
  287. case ElementType.U8:
  288. case ElementType.R4:
  289. case ElementType.R8:
  290. case ElementType.I:
  291. case ElementType.U:
  292. case ElementType.Ptr:
  293. case ElementType.ByRef:
  294. case ElementType.FnPtr:
  295. case ElementType.TypedByRef: return true;
  296. case ElementType.String:
  297. case ElementType.Class:
  298. case ElementType.Array:
  299. case ElementType.SZArray:
  300. case ElementType.Object:
  301. case ElementType.Module:
  302. case ElementType.Var:
  303. case ElementType.MVar: return false;
  304. case ElementType.ValueType:
  305. {
  306. TypeDef typeDef = typeSig.ToTypeDefOrRef().ResolveTypeDef();
  307. if (typeDef == null)
  308. {
  309. throw new Exception($"type:{typeSig} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function");
  310. }
  311. if (typeDef.IsEnum)
  312. {
  313. return true;
  314. }
  315. return CalculateAnalyzeTypeInfoBasic(GetSharedTypeInfo(typeSig)).blittable;
  316. }
  317. case ElementType.GenericInst:
  318. {
  319. GenericInstSig gis = (GenericInstSig)typeSig;
  320. if (!gis.GenericType.IsValueType)
  321. {
  322. return false;
  323. }
  324. TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef();
  325. if (typeDef.IsEnum)
  326. {
  327. return true;
  328. }
  329. return CalculateAnalyzeTypeInfoBasic(GetSharedTypeInfo(typeSig)).blittable;
  330. }
  331. default: throw new NotSupportedException($"{typeSig.ElementType}");
  332. }
  333. }
  334. private AnalyzeTypeInfo CalculateAnalyzeTypeInfoBasic(TypeInfo typeInfo)
  335. {
  336. Debug.Assert(typeInfo.IsStruct);
  337. if (_analyzeTypeInfos.TryGetValue(typeInfo, out var ati))
  338. {
  339. return ati;
  340. }
  341. TypeSig type = typeInfo.Klass;
  342. TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
  343. List<TypeSig> klassInst = type.ToGenericInstSig()?.GenericArguments?.ToList();
  344. GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
  345. var fields = new List<AnalyzeFieldInfo>();
  346. bool blittable = true;
  347. foreach (FieldDef field in typeDef.Fields)
  348. {
  349. if (field.IsStatic)
  350. {
  351. continue;
  352. }
  353. TypeSig fieldType = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
  354. blittable &= IsBlittable(fieldType);
  355. TypeInfo sharedFieldTypeInfo = GetSharedTypeInfo(fieldType);
  356. TypeInfo isoType = ToIsomorphicType(sharedFieldTypeInfo);
  357. fields.Add(new AnalyzeFieldInfo { field = field, type = isoType });
  358. }
  359. //analyzeTypeInfo.blittable = blittable;
  360. //analyzeTypeInfo.packingSize = blittable ? analyzeTypeInfo.originalPackingSize : 0;
  361. ClassLayout sa = typeDef.ClassLayout;
  362. uint originalPackingSize = sa?.PackingSize ?? 0;
  363. var analyzeTypeInfo = new AnalyzeTypeInfo()
  364. {
  365. originalPackingSize = originalPackingSize,
  366. packingSize = blittable && !typeDef.IsAutoLayout ? originalPackingSize : 0,
  367. classSize = sa?.ClassSize ?? 0,
  368. layout = typeDef.IsAutoLayout ? LayoutKind.Auto : (typeDef.IsExplicitLayout ? LayoutKind.Explicit : LayoutKind.Sequential),
  369. fields = fields,
  370. blittable = blittable,
  371. };
  372. _analyzeTypeInfos.Add(typeInfo, analyzeTypeInfo);
  373. analyzeTypeInfo.signature = GetOrCalculateTypeInfoSignature(typeInfo);
  374. if (_signature2Type.TryGetValue(analyzeTypeInfo.signature, out var sharedType))
  375. {
  376. // Debug.Log($"[ToIsomorphicType] type:{type.Klass} ==> sharedType:{sharedType.Klass} signature:{signature} ");
  377. analyzeTypeInfo.isoType = sharedType;
  378. }
  379. else
  380. {
  381. analyzeTypeInfo.isoType = typeInfo;
  382. _signature2Type.Add(analyzeTypeInfo.signature, typeInfo);
  383. }
  384. return analyzeTypeInfo;
  385. }
  386. private string GetOrCalculateTypeInfoSignature(TypeInfo typeInfo)
  387. {
  388. if (!typeInfo.IsStruct)
  389. {
  390. return typeInfo.CreateSigName();
  391. }
  392. var ati = _analyzeTypeInfos[typeInfo];
  393. //if (_analyzeTypeInfos.TryGetValue(typeInfo, out var ati))
  394. //{
  395. // return ati.signature;
  396. //}
  397. //ati = CalculateAnalyzeTypeInfoBasic(typeInfo);
  398. //_analyzeTypeInfos.Add(typeInfo, ati);
  399. if (ati.signature != null)
  400. {
  401. return ati.signature;
  402. }
  403. var sigBuf = new StringBuilder();
  404. if (ati.packingSize != 0 || ati.classSize != 0 || ati.layout != LayoutKind.Sequential || !ati.blittable)
  405. {
  406. sigBuf.Append($"[{ati.classSize}|{ati.packingSize}|{ati.layout}|{(ati.blittable ? 0 : 1)}]");
  407. }
  408. foreach (var field in ati.fields)
  409. {
  410. string fieldOffset = field.field.FieldOffset != null ? field.field.FieldOffset.ToString() + "|" : "";
  411. sigBuf.Append("{" + fieldOffset + GetOrCalculateTypeInfoSignature(ToIsomorphicType(field.type)) + "}");
  412. }
  413. return ati.signature = sigBuf.ToString();
  414. }
  415. private TypeInfo ToIsomorphicType(TypeInfo type)
  416. {
  417. if (!type.IsStruct)
  418. {
  419. return type;
  420. }
  421. return CalculateAnalyzeTypeInfoBasic(type).isoType;
  422. }
  423. private MethodDesc ToIsomorphicMethod(MethodDesc method)
  424. {
  425. var paramInfos = new List<ParamInfo>();
  426. foreach (var paramInfo in method.ParamInfos)
  427. {
  428. paramInfos.Add(new ParamInfo() { Type = ToIsomorphicType(paramInfo.Type) });
  429. }
  430. var mbs = new MethodDesc()
  431. {
  432. MethodDef = method.MethodDef,
  433. ReturnInfo = new ReturnInfo() { Type = ToIsomorphicType(method.ReturnInfo.Type) },
  434. ParamInfos = paramInfos,
  435. };
  436. mbs.Init();
  437. return mbs;
  438. }
  439. private List<MethodDesc> _managed2NativeMethodList;
  440. private List<MethodDesc> _native2ManagedMethodList;
  441. private List<MethodDesc> _adjustThunkMethodList;
  442. private List<TypeInfo> structTypes;
  443. private void BuildAnalyzeTypeInfos()
  444. {
  445. foreach (var type in _structTypes0)
  446. {
  447. ToIsomorphicType(type);
  448. }
  449. structTypes = _signature2Type.Values.ToList();
  450. structTypes.Sort((a, b) => a.TypeId - b.TypeId);
  451. }
  452. private List<MethodDesc> ToUniqueOrderedList(List<MethodDesc> methods)
  453. {
  454. var methodMap = new SortedDictionary<string, MethodDesc>();
  455. foreach (var method in methods)
  456. {
  457. var sharedMethod = ToIsomorphicMethod(method);
  458. var sig = sharedMethod.Sig;
  459. if (!methodMap.TryGetValue(sig, out var _))
  460. {
  461. methodMap.Add(sig, sharedMethod);
  462. }
  463. }
  464. return methodMap.Values.ToList();
  465. }
  466. private static string MakeReversePInvokeSignature(MethodDesc desc, CallingConvention CallingConventionention)
  467. {
  468. string convStr = ((char)('A' + (int)CallingConventionention - 1)).ToString();
  469. return $"{convStr}{desc.Sig}";
  470. }
  471. private static string MakeCalliSignature(MethodDesc desc, CallingConvention CallingConventionention)
  472. {
  473. string convStr = ((char)('A' + Math.Max((int)CallingConventionention - 1, 0))).ToString();
  474. return $"{convStr}{desc.Sig}";
  475. }
  476. private static CallingConvention GetCallingConvention(MethodDef method)
  477. {
  478. var monoPInvokeCallbackAttr = method.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.Name == "MonoPInvokeCallbackAttribute");
  479. if (monoPInvokeCallbackAttr == null)
  480. {
  481. return CallingConvention.Winapi;
  482. }
  483. object delegateTypeSig = monoPInvokeCallbackAttr.ConstructorArguments[0].Value;
  484. TypeDef delegateTypeDef;
  485. if (delegateTypeSig is ClassSig classSig)
  486. {
  487. delegateTypeDef = classSig.TypeDefOrRef.ResolveTypeDefThrow();
  488. }
  489. else if (delegateTypeSig is GenericInstSig genericInstSig)
  490. {
  491. delegateTypeDef = genericInstSig.GenericType.TypeDefOrRef.ResolveTypeDefThrow();
  492. }
  493. else
  494. {
  495. delegateTypeDef = null;
  496. }
  497. if (delegateTypeDef == null)
  498. {
  499. throw new NotSupportedException($"Unsupported delegate type: {delegateTypeSig}");
  500. }
  501. var attr = delegateTypeDef.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.FullName == "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute");
  502. if (attr == null)
  503. {
  504. return CallingConvention.Winapi;
  505. }
  506. var conv = attr.ConstructorArguments[0].Value;
  507. return (CallingConvention)conv;
  508. }
  509. private List<ABIReversePInvokeMethodInfo> BuildABIMethods(List<RawMonoPInvokeCallbackMethodInfo> rawMethods)
  510. {
  511. var methodsBySig = new Dictionary<string, ABIReversePInvokeMethodInfo>();
  512. foreach (var method in rawMethods)
  513. {
  514. var sharedMethod = new MethodDesc
  515. {
  516. MethodDef = method.Method,
  517. ReturnInfo = new ReturnInfo { Type = GetSharedTypeInfo(method.Method.ReturnType) },
  518. ParamInfos = method.Method.Parameters.Select(p => new ParamInfo { Type = GetSharedTypeInfo(p.Type) }).ToList(),
  519. };
  520. sharedMethod.Init();
  521. sharedMethod = ToIsomorphicMethod(sharedMethod);
  522. CallingConvention callingConv = GetCallingConvention(method.Method);
  523. string signature = MakeReversePInvokeSignature(sharedMethod, callingConv);
  524. if (!methodsBySig.TryGetValue(signature, out var arm))
  525. {
  526. arm = new ABIReversePInvokeMethodInfo()
  527. {
  528. Method = sharedMethod,
  529. Signature = signature,
  530. Count = 0,
  531. Callvention = callingConv,
  532. };
  533. methodsBySig.Add(signature, arm);
  534. }
  535. int preserveCount = method.GenerationAttribute != null ? (int)method.GenerationAttribute.ConstructorArguments[0].Value : 1;
  536. arm.Count += preserveCount;
  537. }
  538. var newMethods = methodsBySig.Values.ToList();
  539. newMethods.Sort((a, b) => string.CompareOrdinal(a.Signature, b.Signature));
  540. return newMethods;
  541. }
  542. private List<CalliMethodInfo> BuildCalliMethods(List<CallNativeMethodSignatureInfo> rawMethods)
  543. {
  544. var methodsBySig = new Dictionary<string, CalliMethodInfo>();
  545. foreach (var method in rawMethods)
  546. {
  547. var sharedMethod = new MethodDesc
  548. {
  549. MethodDef = null,
  550. ReturnInfo = new ReturnInfo { Type = GetSharedTypeInfo(method.MethodSig.RetType) },
  551. ParamInfos = method.MethodSig.Params.Select(p => new ParamInfo { Type = GetSharedTypeInfo(p) }).ToList(),
  552. };
  553. sharedMethod.Init();
  554. sharedMethod = ToIsomorphicMethod(sharedMethod);
  555. CallingConvention callingConv = (CallingConvention)((int)((method.Callvention ?? method.MethodSig.CallingConvention) & dnlib.DotNet.CallingConvention.Mask) + 1);
  556. string signature = MakeCalliSignature(sharedMethod, callingConv);
  557. if (!methodsBySig.TryGetValue(signature, out var arm))
  558. {
  559. arm = new CalliMethodInfo()
  560. {
  561. Method = sharedMethod,
  562. Signature = signature,
  563. Callvention = callingConv,
  564. };
  565. methodsBySig.Add(signature, arm);
  566. }
  567. }
  568. var newMethods = methodsBySig.Values.ToList();
  569. newMethods.Sort((a, b) => string.CompareOrdinal(a.Signature, b.Signature));
  570. return newMethods;
  571. }
  572. private void BuildOptimizedMethods()
  573. {
  574. _managed2NativeMethodList = ToUniqueOrderedList(_managed2NativeMethodList0);
  575. _native2ManagedMethodList = ToUniqueOrderedList(_native2ManagedMethodList0);
  576. _adjustThunkMethodList = ToUniqueOrderedList(_adjustThunkMethodList0);
  577. _reversePInvokeMethods = BuildABIMethods(_originalReversePInvokeMethods);
  578. _callidMethods = BuildCalliMethods(_originalCalliMethodSignatures);
  579. }
  580. private void OptimizationTypesAndMethods()
  581. {
  582. BuildAnalyzeTypeInfos();
  583. BuildOptimizedMethods();
  584. Debug.LogFormat("== after optimization struct:{3} managed2native:{0} native2managed:{1} adjustThunk:{2}",
  585. _managed2NativeMethodList.Count, _native2ManagedMethodList.Count, _adjustThunkMethodList.Count, structTypes.Count);
  586. }
  587. private void GenerateCode()
  588. {
  589. var frr = new FileRegionReplace(_templateCode);
  590. List<string> lines = new List<string>(20_0000)
  591. {
  592. "\n",
  593. $"// DEVELOPMENT={(_development ? 1 : 0)}",
  594. "\n"
  595. };
  596. var classInfos = new List<ClassInfo>();
  597. var classTypeSet = new Dictionary<TypeInfo, ClassInfo>();
  598. foreach (var type in structTypes)
  599. {
  600. GenerateClassInfo(type, classTypeSet, classInfos);
  601. }
  602. GenerateStructDefines(classInfos, lines);
  603. // use structTypes0 to generate signature
  604. GenerateStructureSignatureStub(_structTypes0, lines);
  605. foreach (var method in _managed2NativeMethodList)
  606. {
  607. GenerateManaged2NativeMethod(method, lines);
  608. }
  609. GenerateManaged2NativeStub(_managed2NativeMethodList, lines);
  610. foreach (var method in _native2ManagedMethodList)
  611. {
  612. GenerateNative2ManagedMethod(method, lines);
  613. }
  614. GenerateNative2ManagedStub(_native2ManagedMethodList, lines);
  615. foreach (var method in _adjustThunkMethodList)
  616. {
  617. GenerateAdjustThunkMethod(method, lines);
  618. }
  619. GenerateAdjustThunkStub(_adjustThunkMethodList, lines);
  620. GenerateReversePInvokeWrappers(_reversePInvokeMethods, lines);
  621. foreach (var method in _callidMethods)
  622. {
  623. GenerateManaged2NativeFunctionPointerMethod(method, lines);
  624. }
  625. GenerateManaged2NativeFunctionPointerMethodStub(_callidMethods, lines);
  626. frr.Replace("CODE", string.Join("\n", lines));
  627. Directory.CreateDirectory(Path.GetDirectoryName(_outputFile));
  628. frr.Commit(_outputFile);
  629. }
  630. private static string GetIl2cppCallConventionName(CallingConvention conv)
  631. {
  632. switch (conv)
  633. {
  634. case 0:
  635. case CallingConvention.Winapi:
  636. return "DEFAULT_CALL";
  637. case CallingConvention.Cdecl:
  638. return "CDECL";
  639. case CallingConvention.StdCall:
  640. return "STDCALL";
  641. case CallingConvention.ThisCall:
  642. return "THISCALL";
  643. case CallingConvention.FastCall:
  644. return "FASTCALL";
  645. default:
  646. throw new NotSupportedException($"Unsupported CallingConvention {conv}");
  647. }
  648. }
  649. private void GenerateReversePInvokeWrappers(List<ABIReversePInvokeMethodInfo> methods, List<string> lines)
  650. {
  651. int methodIndex = 0;
  652. var stubCodes = new List<string>();
  653. foreach (var methodInfo in methods)
  654. {
  655. MethodDesc method = methodInfo.Method;
  656. string il2cppCallConventionName = GetIl2cppCallConventionName(methodInfo.Callvention);
  657. string paramDeclaringListWithoutMethodInfoStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}"));
  658. string paramNameListWithoutMethodInfoStr = string.Join(", ", method.ParamInfos.Select(p => $"__arg{p.Index}").Concat(new string[] { "method" }));
  659. string paramTypeListWithMethodInfoStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()}").Concat(new string[] { "const MethodInfo*" }));
  660. string methodTypeDef = $"typedef {method.ReturnInfo.Type.GetTypeName()} (*Callback)({paramTypeListWithMethodInfoStr})";
  661. for (int i = 0; i < methodInfo.Count; i++, methodIndex++)
  662. {
  663. lines.Add($@"
  664. {method.ReturnInfo.Type.GetTypeName()} {il2cppCallConventionName} __ReversePInvokeMethod_{methodIndex}({paramDeclaringListWithoutMethodInfoStr})
  665. {{
  666. il2cpp::vm::ScopedThreadAttacher _vmThreadHelper;
  667. const MethodInfo* method = InterpreterModule::GetMethodInfoByReversePInvokeWrapperIndex({methodIndex});
  668. {methodTypeDef};
  669. {(method.ReturnInfo.IsVoid ? "" : "return ")}((Callback)(method->methodPointerCallByInterp))({paramNameListWithoutMethodInfoStr});
  670. }}
  671. ");
  672. stubCodes.Add($"\t{{\"{methodInfo.Signature}\", (Il2CppMethodPointer)__ReversePInvokeMethod_{methodIndex}}},");
  673. }
  674. Debug.Log($"[ReversePInvokeWrap.Generator] method:{method.MethodDef} wrapperCount:{methodInfo.Count}");
  675. }
  676. lines.Add(@"
  677. const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStub[]
  678. {
  679. ");
  680. lines.AddRange(stubCodes);
  681. lines.Add(@"
  682. {nullptr, nullptr},
  683. };
  684. ");
  685. }
  686. public void Generate()
  687. {
  688. PrepareMethodBridges();
  689. CollectTypesAndMethods();
  690. OptimizationTypesAndMethods();
  691. GenerateCode();
  692. }
  693. private void CollectStructDefs(List<MethodDesc> methods, HashSet<TypeInfo> structTypes)
  694. {
  695. foreach (var method in methods)
  696. {
  697. foreach(var paramInfo in method.ParamInfos)
  698. {
  699. if (paramInfo.Type.IsStruct)
  700. {
  701. structTypes.Add(paramInfo.Type);
  702. if (paramInfo.Type.Klass.ContainsGenericParameter)
  703. {
  704. throw new Exception($"[CollectStructDefs] method:{method.MethodDef} type:{paramInfo.Type.Klass} contains generic parameter");
  705. }
  706. }
  707. }
  708. if (method.ReturnInfo.Type.IsStruct)
  709. {
  710. structTypes.Add(method.ReturnInfo.Type);
  711. if (method.ReturnInfo.Type.Klass.ContainsGenericParameter)
  712. {
  713. throw new Exception($"[CollectStructDefs] method:{method.MethodDef} type:{method.ReturnInfo.Type.Klass} contains generic parameter");
  714. }
  715. }
  716. }
  717. }
  718. private void CollectStructDefs(List<MethodSig> methods, HashSet<TypeInfo> structTypes)
  719. {
  720. ICorLibTypes corLibTypes = _genericMethods[0].Method.Module.CorLibTypes;
  721. foreach (var method in methods)
  722. {
  723. foreach (var paramInfo in method.Params)
  724. {
  725. var paramType = GetSharedTypeInfo(MetaUtil.ToShareTypeSig(corLibTypes, paramInfo));
  726. if (paramType.IsStruct)
  727. {
  728. structTypes.Add(paramType);
  729. if (paramType.Klass.ContainsGenericParameter)
  730. {
  731. throw new Exception($"[CollectStructDefs] method:{method} type:{paramType.Klass} contains generic parameter");
  732. }
  733. }
  734. }
  735. var returnType = GetSharedTypeInfo(MetaUtil.ToShareTypeSig(corLibTypes, method.RetType));
  736. if (returnType.IsStruct)
  737. {
  738. structTypes.Add(returnType);
  739. if (returnType.Klass.ContainsGenericParameter)
  740. {
  741. throw new Exception($"[CollectStructDefs] method:{method} type:{returnType.Klass} contains generic parameter");
  742. }
  743. }
  744. }
  745. }
  746. class FieldInfo
  747. {
  748. public FieldDef field;
  749. public TypeInfo type;
  750. }
  751. class ClassInfo
  752. {
  753. public TypeInfo type;
  754. public List<AnalyzeFieldInfo> fields;
  755. public uint packingSize;
  756. public uint classSize;
  757. public LayoutKind layout;
  758. public bool blittable;
  759. }
  760. private void GenerateClassInfo(TypeInfo type, Dictionary<TypeInfo, ClassInfo> typeSet, List<ClassInfo> classInfos)
  761. {
  762. if (typeSet.ContainsKey(type))
  763. {
  764. return;
  765. }
  766. AnalyzeTypeInfo ati = CalculateAnalyzeTypeInfoBasic(type);
  767. //TypeSig typeSig = type.Klass;
  768. //var fields = new List<FieldInfo>();
  769. //TypeDef typeDef = typeSig.ToTypeDefOrRef().ResolveTypeDefThrow();
  770. //List<TypeSig> klassInst = typeSig.ToGenericInstSig()?.GenericArguments?.ToList();
  771. //GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
  772. //ClassLayout sa = typeDef.ClassLayout;
  773. //ICorLibTypes corLibTypes = typeDef.Module.CorLibTypes;
  774. //bool blittable = true;
  775. //foreach (FieldDef field in typeDef.Fields)
  776. //{
  777. // if (field.IsStatic)
  778. // {
  779. // continue;
  780. // }
  781. // TypeSig fieldType = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
  782. // fieldType = MetaUtil.ToShareTypeSig(corLibTypes, fieldType);
  783. // var fieldTypeInfo = ToIsomorphicType(GetSharedTypeInfo(fieldType));
  784. // if (fieldTypeInfo.IsStruct)
  785. // {
  786. // GenerateClassInfo(fieldTypeInfo, typeSet, classInfos);
  787. // }
  788. // blittable &= IsBlittable(fieldType, fieldTypeInfo, typeSet);
  789. // fields.Add(new FieldInfo { field = field, type = fieldTypeInfo });
  790. //}
  791. foreach (var field in ati.fields)
  792. {
  793. if (field.type.IsStruct)
  794. {
  795. GenerateClassInfo(field.type, typeSet, classInfos);
  796. }
  797. }
  798. var classInfo = new ClassInfo()
  799. {
  800. type = type,
  801. fields = ati.fields,
  802. packingSize = ati.packingSize,
  803. classSize = ati.classSize,
  804. layout = ati.layout,
  805. blittable = ati.blittable,
  806. };
  807. typeSet.Add(type, classInfo);
  808. classInfos.Add(classInfo);
  809. }
  810. private void GenerateStructDefines(List<ClassInfo> classInfos, List<string> lines)
  811. {
  812. foreach (var ci in classInfos)
  813. {
  814. lines.Add($"// {ci.type.Klass}");
  815. uint packingSize = ci.packingSize;
  816. uint classSize = ci.classSize;
  817. if (ci.layout == LayoutKind.Explicit)
  818. {
  819. lines.Add($"struct {ci.type.GetTypeName()} {{");
  820. lines.Add("\tunion {");
  821. if (classSize > 0)
  822. {
  823. lines.Add($"\tstruct {{ char __fieldSize_offsetPadding[{classSize}];}};");
  824. }
  825. int index = 0;
  826. foreach (var field in ci.fields)
  827. {
  828. uint offset = field.field.FieldOffset.Value;
  829. string fieldName = $"__{index}";
  830. string commentFieldName = $"{field.field.Name}";
  831. lines.Add("\t#pragma pack(push, 1)");
  832. lines.Add($"\tstruct {{ {(offset > 0 ? $"char {fieldName}_offsetPadding[{offset}]; " : "")}{field.type.GetTypeName()} {fieldName};}}; // {commentFieldName}");
  833. lines.Add($"\t#pragma pack(pop)");
  834. if (packingSize > 0)
  835. {
  836. lines.Add($"\t#pragma pack(push, {packingSize})");
  837. }
  838. lines.Add($"\tstruct {{ {(offset > 0 ? $"char {fieldName}_offsetPadding_forAlignmentOnly[{offset}]; " : "")}{field.type.GetTypeName()} {fieldName}_forAlignmentOnly;}}; // {commentFieldName}");
  839. if (packingSize > 0)
  840. {
  841. lines.Add($"\t#pragma pack(pop)");
  842. }
  843. ++index;
  844. }
  845. lines.Add("\t};");
  846. lines.Add("};");
  847. }
  848. else
  849. {
  850. if (packingSize != 0)
  851. {
  852. lines.Add($"#pragma pack(push, {packingSize})");
  853. }
  854. lines.Add($"{(classSize > 0 ? "union" : "struct")} {ci.type.GetTypeName()} {{");
  855. if (classSize > 0)
  856. {
  857. lines.Add($"\tstruct {{ char __fieldSize_offsetPadding[{classSize}];}};");
  858. lines.Add("\tstruct {");
  859. }
  860. int index = 0;
  861. foreach (var field in ci.fields)
  862. {
  863. string fieldName = $"__{index}";
  864. string commentFieldName = $"{field.field.Name}";
  865. lines.Add($"\t{field.type.GetTypeName()} {fieldName}; // {commentFieldName}");
  866. ++index;
  867. }
  868. if (classSize > 0)
  869. {
  870. lines.Add("\t};");
  871. }
  872. lines.Add("};");
  873. if (packingSize != 0)
  874. {
  875. lines.Add($"#pragma pack(pop)");
  876. }
  877. }
  878. }
  879. }
  880. private const string SigOfObj = "u";
  881. private static string ToFullName(TypeSig type)
  882. {
  883. type = type.RemovePinnedAndModifiers();
  884. switch (type.ElementType)
  885. {
  886. case ElementType.Void: return "v";
  887. case ElementType.Boolean: return "u1";
  888. case ElementType.I1: return "i1";
  889. case ElementType.U1: return "u1";
  890. case ElementType.I2: return "i2";
  891. case ElementType.Char:
  892. case ElementType.U2: return "u2";
  893. case ElementType.I4: return "i4";
  894. case ElementType.U4: return "u4";
  895. case ElementType.I8: return "i8";
  896. case ElementType.U8: return "u8";
  897. case ElementType.R4: return "r4";
  898. case ElementType.R8: return "r8";
  899. case ElementType.I: return "i";
  900. case ElementType.U:
  901. case ElementType.String:
  902. case ElementType.Ptr:
  903. case ElementType.ByRef:
  904. case ElementType.Class:
  905. case ElementType.Array:
  906. case ElementType.SZArray:
  907. case ElementType.FnPtr:
  908. case ElementType.Object:
  909. return SigOfObj;
  910. case ElementType.Module:
  911. case ElementType.Var:
  912. case ElementType.MVar:
  913. throw new NotSupportedException($"ToFullName type:{type}");
  914. case ElementType.TypedByRef: return TypeInfo.strTypedByRef;
  915. case ElementType.ValueType:
  916. {
  917. TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef();
  918. if (typeDef == null)
  919. {
  920. throw new Exception($"type:{type} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function");
  921. }
  922. if (typeDef.IsEnum)
  923. {
  924. return ToFullName(typeDef.GetEnumUnderlyingType());
  925. }
  926. return ToValueTypeFullName((ClassOrValueTypeSig)type);
  927. }
  928. case ElementType.GenericInst:
  929. {
  930. GenericInstSig gis = (GenericInstSig)type;
  931. if (!gis.GenericType.IsValueType)
  932. {
  933. return SigOfObj;
  934. }
  935. TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef();
  936. if (typeDef.IsEnum)
  937. {
  938. return ToFullName(typeDef.GetEnumUnderlyingType());
  939. }
  940. return $"{ToValueTypeFullName(gis.GenericType)}<{string.Join(",", gis.GenericArguments.Select(a => ToFullName(a)))}>";
  941. }
  942. default: throw new NotSupportedException($"{type.ElementType}");
  943. }
  944. }
  945. private static bool IsSystemOrUnityAssembly(ModuleDef module)
  946. {
  947. if (module.IsCoreLibraryModule == true)
  948. {
  949. return true;
  950. }
  951. string assName = module.Assembly.Name.String;
  952. return assName.StartsWith("System.") || assName.StartsWith("UnityEngine.");
  953. }
  954. private static string ToValueTypeFullName(ClassOrValueTypeSig type)
  955. {
  956. TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef();
  957. if (typeDef == null)
  958. {
  959. throw new Exception($"type:{type} resolve fail");
  960. }
  961. if (typeDef.DeclaringType != null)
  962. {
  963. return $"{ToValueTypeFullName((ClassOrValueTypeSig)typeDef.DeclaringType.ToTypeSig())}/{typeDef.Name}";
  964. }
  965. if (IsSystemOrUnityAssembly(typeDef.Module))
  966. {
  967. return type.FullName;
  968. }
  969. return $"{Path.GetFileNameWithoutExtension(typeDef.Module.Name)}:{typeDef.FullName}";
  970. }
  971. private void GenerateStructureSignatureStub(List<TypeInfo> types, List<string> lines)
  972. {
  973. lines.Add("const FullName2Signature hybridclr::interpreter::g_fullName2SignatureStub[] = {");
  974. foreach (var type in types)
  975. {
  976. TypeInfo isoType = ToIsomorphicType(type);
  977. lines.Add($"\t{{\"{ToFullName(type.Klass)}\", \"{isoType.CreateSigName()}\"}},");
  978. }
  979. lines.Add("\t{ nullptr, nullptr},");
  980. lines.Add("};");
  981. }
  982. private void GenerateManaged2NativeStub(List<MethodDesc> methods, List<string> lines)
  983. {
  984. lines.Add($@"
  985. const Managed2NativeMethodInfo hybridclr::interpreter::g_managed2nativeStub[] =
  986. {{
  987. ");
  988. foreach (var method in methods)
  989. {
  990. lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", __M2N_{method.CreateInvokeSigName()}}},");
  991. }
  992. lines.Add($"\t{{nullptr, nullptr}},");
  993. lines.Add("};");
  994. }
  995. private void GenerateNative2ManagedStub(List<MethodDesc> methods, List<string> lines)
  996. {
  997. lines.Add($@"
  998. const Native2ManagedMethodInfo hybridclr::interpreter::g_native2managedStub[] =
  999. {{
  1000. ");
  1001. foreach (var method in methods)
  1002. {
  1003. lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_{method.CreateInvokeSigName()}}},");
  1004. }
  1005. lines.Add($"\t{{nullptr, nullptr}},");
  1006. lines.Add("};");
  1007. }
  1008. private void GenerateAdjustThunkStub(List<MethodDesc> methods, List<string> lines)
  1009. {
  1010. lines.Add($@"
  1011. const NativeAdjustThunkMethodInfo hybridclr::interpreter::g_adjustThunkStub[] =
  1012. {{
  1013. ");
  1014. foreach (var method in methods)
  1015. {
  1016. lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_AdjustorThunk_{method.CreateCallSigName()}}},");
  1017. }
  1018. lines.Add($"\t{{nullptr, nullptr}},");
  1019. lines.Add("};");
  1020. }
  1021. private string GetManaged2NativePassParam(TypeInfo type, string varName)
  1022. {
  1023. return $"M2NFromValueOrAddress<{type.GetTypeName()}>({varName})";
  1024. }
  1025. private string GetNative2ManagedPassParam(TypeInfo type, string varName)
  1026. {
  1027. return type.NeedExpandValue() ? $"(uint64_t)({varName})" : $"N2MAsUint64ValueOrAddress<{type.GetTypeName()}>({varName})";
  1028. }
  1029. private void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines)
  1030. {
  1031. string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
  1032. string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => GetManaged2NativePassParam(p.Type, $"localVarBase+argVarIndexs[{p.Index}]")).Concat(new string[] { "method" }));
  1033. lines.Add($@"
  1034. static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)
  1035. {{
  1036. typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr});
  1037. {(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr});
  1038. }}
  1039. ");
  1040. }
  1041. private string GenerateArgumentSizeAndOffset(List<ParamInfo> paramInfos)
  1042. {
  1043. StringBuilder s = new StringBuilder();
  1044. int index = 0;
  1045. foreach (var param in paramInfos)
  1046. {
  1047. s.AppendLine($"\tconstexpr int __ARG_OFFSET_{index}__ = {(index > 0 ? $"__ARG_OFFSET_{index - 1}__ + __ARG_SIZE_{index-1}__" : "0")};");
  1048. s.AppendLine($"\tconstexpr int __ARG_SIZE_{index}__ = (sizeof(__arg{index}) + 7)/8;");
  1049. index++;
  1050. }
  1051. s.AppendLine($"\tconstexpr int __TOTAL_ARG_SIZE__ = {(paramInfos.Count > 0 ? $"__ARG_OFFSET_{index-1}__ + __ARG_SIZE_{index-1}__" : "1")};");
  1052. return s.ToString();
  1053. }
  1054. private string GenerateCopyArgumentToInterpreterStack(List<ParamInfo> paramInfos)
  1055. {
  1056. StringBuilder s = new StringBuilder();
  1057. int index = 0;
  1058. foreach (var param in paramInfos)
  1059. {
  1060. if (param.Type.IsPrimitiveType)
  1061. {
  1062. if (param.Type.NeedExpandValue())
  1063. {
  1064. s.AppendLine($"\targs[__ARG_OFFSET_{index}__].u64 = __arg{index};");
  1065. }
  1066. else
  1067. {
  1068. s.AppendLine($"\t*({param.Type.GetTypeName()}*)(args + __ARG_OFFSET_{index}__) = __arg{index};");
  1069. }
  1070. }
  1071. else
  1072. {
  1073. s.AppendLine($"\t*({param.Type.GetTypeName()}*)(args + __ARG_OFFSET_{index}__) = __arg{index};");
  1074. }
  1075. index++;
  1076. }
  1077. return s.ToString();
  1078. }
  1079. private void GenerateNative2ManagedMethod0(MethodDesc method, bool adjustorThunk, List<string> lines)
  1080. {
  1081. string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
  1082. lines.Add($@"
  1083. static {method.ReturnInfo.Type.GetTypeName()} __N2M_{(adjustorThunk ? "AdjustorThunk_" : "")}{method.CreateCallSigName()}({paramListStr})
  1084. {{
  1085. {(adjustorThunk ? "__arg0 += sizeof(Il2CppObject);" : "")}
  1086. {GenerateArgumentSizeAndOffset(method.ParamInfos)}
  1087. StackObject args[__TOTAL_ARG_SIZE__];
  1088. {GenerateCopyArgumentToInterpreterStack(method.ParamInfos)}
  1089. {(method.ReturnInfo.IsVoid ? "Interpreter::Execute(method, args, nullptr);" : $"{method.ReturnInfo.Type.GetTypeName()} ret; Interpreter::Execute(method, args, &ret); return ret;")}
  1090. }}
  1091. ");
  1092. }
  1093. private void GenerateNative2ManagedMethod(MethodDesc method, List<string> lines)
  1094. {
  1095. GenerateNative2ManagedMethod0(method, false, lines);
  1096. }
  1097. private void GenerateAdjustThunkMethod(MethodDesc method, List<string> lines)
  1098. {
  1099. GenerateNative2ManagedMethod0(method, true, lines);
  1100. }
  1101. private void GenerateManaged2NativeFunctionPointerMethod(CalliMethodInfo methodInfo, List<string> lines)
  1102. {
  1103. MethodDesc method = methodInfo.Method;
  1104. string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}"));
  1105. string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => GetManaged2NativePassParam(p.Type, $"localVarBase+argVarIndexs[{p.Index}]")));
  1106. string il2cppCallConventionName = GetIl2cppCallConventionName(methodInfo.Callvention);
  1107. lines.Add($@"
  1108. static void __M2NF_{methodInfo.Signature}(Il2CppMethodPointer methodPointer, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)
  1109. {{
  1110. typedef {method.ReturnInfo.Type.GetTypeName()} ({il2cppCallConventionName} *NativeMethod)({paramListStr});
  1111. {(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(methodPointer))({paramNameListStr});
  1112. }}
  1113. ");
  1114. }
  1115. private void GenerateManaged2NativeFunctionPointerMethodStub(List<CalliMethodInfo> calliMethodSignatures, List<string> lines)
  1116. {
  1117. lines.Add(@"
  1118. const Managed2NativeFunctionPointerCallData hybridclr::interpreter::g_managed2NativeFunctionPointerCallStub[]
  1119. {
  1120. ");
  1121. foreach (var method in calliMethodSignatures)
  1122. {
  1123. lines.Add($"\t{{\"{method.Signature}\", __M2NF_{method.Signature}}},");
  1124. }
  1125. lines.Add(@"
  1126. {nullptr, nullptr},
  1127. };
  1128. ");
  1129. }
  1130. }
  1131. }