MonoMethod.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. //
  2. // System.Reflection/MonoMethod.cs
  3. // The class used to represent methods from the mono runtime.
  4. //
  5. // Author:
  6. // Paolo Molaro ([email protected])
  7. //
  8. // (C) 2001 Ximian, Inc. http://www.ximian.com
  9. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Collections.Generic;
  31. using System.Globalization;
  32. using System.Runtime.CompilerServices;
  33. using System.Runtime.InteropServices;
  34. using System.Runtime.Serialization;
  35. using System.Reflection.Emit;
  36. using System.Security;
  37. using System.Threading;
  38. using System.Text;
  39. namespace System.Reflection {
  40. internal struct MonoMethodInfo
  41. {
  42. #pragma warning disable 649
  43. private Type parent;
  44. private Type ret;
  45. internal MethodAttributes attrs;
  46. internal MethodImplAttributes iattrs;
  47. private CallingConventions callconv;
  48. #pragma warning restore 649
  49. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  50. static extern void get_method_info (IntPtr handle, out MonoMethodInfo info);
  51. internal static MonoMethodInfo GetMethodInfo (IntPtr handle)
  52. {
  53. MonoMethodInfo info;
  54. MonoMethodInfo.get_method_info (handle, out info);
  55. return info;
  56. }
  57. internal static Type GetDeclaringType (IntPtr handle)
  58. {
  59. return GetMethodInfo (handle).parent;
  60. }
  61. internal static Type GetReturnType (IntPtr handle)
  62. {
  63. return GetMethodInfo (handle).ret;
  64. }
  65. internal static MethodAttributes GetAttributes (IntPtr handle)
  66. {
  67. return GetMethodInfo (handle).attrs;
  68. }
  69. internal static CallingConventions GetCallingConvention (IntPtr handle)
  70. {
  71. return GetMethodInfo (handle).callconv;
  72. }
  73. internal static MethodImplAttributes GetMethodImplementationFlags (IntPtr handle)
  74. {
  75. return GetMethodInfo (handle).iattrs;
  76. }
  77. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  78. static extern ParameterInfo[] get_parameter_info (IntPtr handle, MemberInfo member);
  79. static internal ParameterInfo[] GetParametersInfo (IntPtr handle, MemberInfo member)
  80. {
  81. return get_parameter_info (handle, member);
  82. }
  83. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  84. static extern UnmanagedMarshal get_retval_marshal (IntPtr handle);
  85. static internal ParameterInfo GetReturnParameterInfo (MonoMethod method)
  86. {
  87. return new ParameterInfo (GetReturnType (method.mhandle), method, get_retval_marshal (method.mhandle));
  88. }
  89. };
  90. /*
  91. * Note: most of this class needs to be duplicated for the contructor, since
  92. * the .NET reflection class hierarchy is so broken.
  93. */
  94. [Serializable()]
  95. internal class MonoMethod : MethodInfo, ISerializable
  96. {
  97. #pragma warning disable 649
  98. internal IntPtr mhandle;
  99. string name;
  100. Type reftype;
  101. #pragma warning restore 649
  102. internal MonoMethod () {
  103. }
  104. internal MonoMethod (RuntimeMethodHandle mhandle) {
  105. this.mhandle = mhandle.Value;
  106. }
  107. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  108. internal static extern string get_name (MethodBase method);
  109. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  110. internal static extern MonoMethod get_base_method (MonoMethod method, bool definition);
  111. public override MethodInfo GetBaseDefinition ()
  112. {
  113. return get_base_method (this, true);
  114. }
  115. internal override MethodInfo GetBaseMethod ()
  116. {
  117. return get_base_method (this, false);
  118. }
  119. public override ParameterInfo ReturnParameter {
  120. get {
  121. return MonoMethodInfo.GetReturnParameterInfo (this);
  122. }
  123. }
  124. public override Type ReturnType {
  125. get {
  126. return MonoMethodInfo.GetReturnType (mhandle);
  127. }
  128. }
  129. public override ICustomAttributeProvider ReturnTypeCustomAttributes {
  130. get {
  131. return MonoMethodInfo.GetReturnParameterInfo (this);
  132. }
  133. }
  134. public override MethodImplAttributes GetMethodImplementationFlags ()
  135. {
  136. return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
  137. }
  138. public override ParameterInfo[] GetParameters ()
  139. {
  140. ParameterInfo[] src = MonoMethodInfo.GetParametersInfo (mhandle, this);
  141. ParameterInfo[] res = new ParameterInfo [src.Length];
  142. src.CopyTo (res, 0);
  143. return res;
  144. }
  145. /*
  146. * InternalInvoke() receives the parameters correctly converted by the
  147. * binder to match the types of the method signature.
  148. */
  149. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  150. internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
  151. public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  152. {
  153. if (binder == null)
  154. binder = Binder.DefaultBinder;
  155. /*Avoid allocating an array every time*/
  156. ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
  157. if ((parameters == null && pinfo.Length != 0) || (parameters != null && parameters.Length != pinfo.Length))
  158. throw new TargetParameterCountException ("parameters do not match signature");
  159. if ((invokeAttr & BindingFlags.ExactBinding) == 0) {
  160. if (!Binder.ConvertArgs (binder, parameters, pinfo, culture))
  161. throw new ArgumentException ("failed to convert parameters");
  162. } else {
  163. for (int i = 0; i < pinfo.Length; i++)
  164. if (parameters[i].GetType() != pinfo[i].ParameterType)
  165. throw new ArgumentException ("parameters do not match signature");
  166. }
  167. #if !NET_2_1
  168. if (SecurityManager.SecurityEnabled) {
  169. // sadly Attributes doesn't tell us which kind of security action this is so
  170. // we must do it the hard way - and it also means that we can skip calling
  171. // Attribute (which is another an icall)
  172. SecurityManager.ReflectedLinkDemandInvoke (this);
  173. }
  174. #endif
  175. if (ContainsGenericParameters)
  176. throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.");
  177. Exception exc;
  178. object o = null;
  179. try {
  180. // The ex argument is used to distinguish exceptions thrown by the icall
  181. // from the exceptions thrown by the called method (which need to be
  182. // wrapped in TargetInvocationException).
  183. o = InternalInvoke (obj, parameters, out exc);
  184. } catch (ThreadAbortException) {
  185. throw;
  186. #if NET_2_1
  187. } catch (MethodAccessException) {
  188. throw;
  189. #endif
  190. } catch (Exception e) {
  191. throw new TargetInvocationException (e);
  192. }
  193. if (exc != null)
  194. throw exc;
  195. return o;
  196. }
  197. public override RuntimeMethodHandle MethodHandle {
  198. get {return new RuntimeMethodHandle (mhandle);}
  199. }
  200. public override MethodAttributes Attributes {
  201. get {
  202. return MonoMethodInfo.GetAttributes (mhandle);
  203. }
  204. }
  205. public override CallingConventions CallingConvention {
  206. get {
  207. return MonoMethodInfo.GetCallingConvention (mhandle);
  208. }
  209. }
  210. public override Type ReflectedType {
  211. get {
  212. return reftype;
  213. }
  214. }
  215. public override Type DeclaringType {
  216. get {
  217. return MonoMethodInfo.GetDeclaringType (mhandle);
  218. }
  219. }
  220. public override string Name {
  221. get {
  222. if (name != null)
  223. return name;
  224. return get_name (this);
  225. }
  226. }
  227. public override bool IsDefined (Type attributeType, bool inherit) {
  228. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  229. }
  230. public override object[] GetCustomAttributes( bool inherit) {
  231. return MonoCustomAttrs.GetCustomAttributes (this, inherit);
  232. }
  233. public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
  234. return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
  235. }
  236. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  237. internal static extern DllImportAttribute GetDllImportAttribute (IntPtr mhandle);
  238. internal object[] GetPseudoCustomAttributes ()
  239. {
  240. int count = 0;
  241. /* MS.NET doesn't report MethodImplAttribute */
  242. MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
  243. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  244. count ++;
  245. if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
  246. count ++;
  247. if (count == 0)
  248. return null;
  249. object[] attrs = new object [count];
  250. count = 0;
  251. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  252. attrs [count ++] = new PreserveSigAttribute ();
  253. if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) {
  254. DllImportAttribute attr = GetDllImportAttribute (mhandle);
  255. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  256. attr.PreserveSig = true;
  257. attrs [count ++] = attr;
  258. }
  259. return attrs;
  260. }
  261. static bool ShouldPrintFullName (Type type) {
  262. return type.IsClass && (!type.IsPointer ||
  263. (!type.GetElementType ().IsPrimitive && !type.GetElementType ().IsNested));
  264. }
  265. public override string ToString () {
  266. StringBuilder sb = new StringBuilder ();
  267. Type retType = ReturnType;
  268. if (ShouldPrintFullName (retType))
  269. sb.Append (retType.ToString ());
  270. else
  271. sb.Append (retType.Name);
  272. sb.Append (" ");
  273. sb.Append (Name);
  274. if (IsGenericMethod) {
  275. Type[] gen_params = GetGenericArguments ();
  276. sb.Append ("[");
  277. for (int j = 0; j < gen_params.Length; j++) {
  278. if (j > 0)
  279. sb.Append (",");
  280. sb.Append (gen_params [j].Name);
  281. }
  282. sb.Append ("]");
  283. }
  284. sb.Append ("(");
  285. ParameterInfo[] p = GetParameters ();
  286. for (int i = 0; i < p.Length; ++i) {
  287. if (i > 0)
  288. sb.Append (", ");
  289. Type pt = p[i].ParameterType;
  290. bool byref = pt.IsByRef;
  291. if (byref)
  292. pt = pt.GetElementType ();
  293. if (ShouldPrintFullName (pt))
  294. sb.Append (pt.ToString ());
  295. else
  296. sb.Append (pt.Name);
  297. if (byref)
  298. sb.Append (" ByRef");
  299. }
  300. if ((CallingConvention & CallingConventions.VarArgs) != 0) {
  301. if (p.Length > 0)
  302. sb.Append (", ");
  303. sb.Append ("...");
  304. }
  305. sb.Append (")");
  306. return sb.ToString ();
  307. }
  308. // ISerializable
  309. public void GetObjectData(SerializationInfo info, StreamingContext context)
  310. {
  311. Type[] genericArguments = IsGenericMethod && !IsGenericMethodDefinition
  312. ? GetGenericArguments () : null;
  313. MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Method, genericArguments);
  314. }
  315. public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
  316. {
  317. if (methodInstantiation == null)
  318. throw new ArgumentNullException ("methodInstantiation");
  319. if (!IsGenericMethodDefinition)
  320. throw new InvalidOperationException ("not a generic method definition");
  321. /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
  322. if (GetGenericArguments ().Length != methodInstantiation.Length)
  323. throw new ArgumentException ("Incorrect length");
  324. bool hasUserType = false;
  325. foreach (Type type in methodInstantiation) {
  326. if (type == null)
  327. throw new ArgumentNullException ();
  328. if (!(type is MonoType))
  329. hasUserType = true;
  330. }
  331. if (hasUserType)
  332. return new MethodOnTypeBuilderInst (this, methodInstantiation);
  333. MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
  334. if (ret == null)
  335. throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
  336. return ret;
  337. }
  338. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  339. extern MethodInfo MakeGenericMethod_impl (Type [] types);
  340. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  341. public override extern Type [] GetGenericArguments ();
  342. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  343. extern MethodInfo GetGenericMethodDefinition_impl ();
  344. public override MethodInfo GetGenericMethodDefinition ()
  345. {
  346. MethodInfo res = GetGenericMethodDefinition_impl ();
  347. if (res == null)
  348. throw new InvalidOperationException ();
  349. return res;
  350. }
  351. public override extern bool IsGenericMethodDefinition {
  352. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  353. get;
  354. }
  355. public override extern bool IsGenericMethod {
  356. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  357. get;
  358. }
  359. public override bool ContainsGenericParameters {
  360. get {
  361. if (IsGenericMethod) {
  362. foreach (Type arg in GetGenericArguments ())
  363. if (arg.ContainsGenericParameters)
  364. return true;
  365. }
  366. return DeclaringType.ContainsGenericParameters;
  367. }
  368. }
  369. public override MethodBody GetMethodBody () {
  370. return GetMethodBody (mhandle);
  371. }
  372. #if NET_4_0
  373. public override IList<CustomAttributeData> GetCustomAttributesData () {
  374. return CustomAttributeData.GetCustomAttributes (this);
  375. }
  376. #endif
  377. }
  378. internal class MonoCMethod : ConstructorInfo, ISerializable
  379. {
  380. #pragma warning disable 649
  381. internal IntPtr mhandle;
  382. string name;
  383. Type reftype;
  384. #pragma warning restore 649
  385. public override MethodImplAttributes GetMethodImplementationFlags ()
  386. {
  387. return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
  388. }
  389. public override ParameterInfo[] GetParameters ()
  390. {
  391. return MonoMethodInfo.GetParametersInfo (mhandle, this);
  392. }
  393. /*
  394. * InternalInvoke() receives the parameters corretcly converted by the binder
  395. * to match the types of the method signature.
  396. */
  397. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  398. internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
  399. public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  400. {
  401. if (binder == null)
  402. binder = Binder.DefaultBinder;
  403. ParameterInfo[] pinfo = GetParameters ();
  404. if ((parameters == null && pinfo.Length != 0) || (parameters != null && parameters.Length != pinfo.Length))
  405. throw new TargetParameterCountException ("parameters do not match signature");
  406. if ((invokeAttr & BindingFlags.ExactBinding) == 0) {
  407. if (!Binder.ConvertArgs (binder, parameters, pinfo, culture))
  408. throw new ArgumentException ("failed to convert parameters");
  409. } else {
  410. for (int i = 0; i < pinfo.Length; i++)
  411. if (parameters[i].GetType() != pinfo[i].ParameterType)
  412. throw new ArgumentException ("parameters do not match signature");
  413. }
  414. #if !NET_2_1
  415. if (SecurityManager.SecurityEnabled) {
  416. // sadly Attributes doesn't tell us which kind of security action this is so
  417. // we must do it the hard way - and it also means that we can skip calling
  418. // Attribute (which is another an icall)
  419. SecurityManager.ReflectedLinkDemandInvoke (this);
  420. }
  421. #endif
  422. if (obj == null && DeclaringType.ContainsGenericParameters)
  423. throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
  424. if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) {
  425. throw new MemberAccessException (String.Format ("Cannot create an instance of {0} because it is an abstract class", DeclaringType));
  426. }
  427. Exception exc = null;
  428. object o = null;
  429. try {
  430. o = InternalInvoke (obj, parameters, out exc);
  431. #if NET_2_1
  432. } catch (MethodAccessException) {
  433. throw;
  434. #endif
  435. } catch (Exception e) {
  436. throw new TargetInvocationException (e);
  437. }
  438. if (exc != null)
  439. throw exc;
  440. return (obj == null) ? o : null;
  441. }
  442. public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
  443. return Invoke (null, invokeAttr, binder, parameters, culture);
  444. }
  445. public override RuntimeMethodHandle MethodHandle {
  446. get {return new RuntimeMethodHandle (mhandle);}
  447. }
  448. public override MethodAttributes Attributes {
  449. get {
  450. return MonoMethodInfo.GetAttributes (mhandle);
  451. }
  452. }
  453. public override CallingConventions CallingConvention {
  454. get {
  455. return MonoMethodInfo.GetCallingConvention (mhandle);
  456. }
  457. }
  458. public override Type ReflectedType {
  459. get {
  460. return reftype;
  461. }
  462. }
  463. public override Type DeclaringType {
  464. get {
  465. return MonoMethodInfo.GetDeclaringType (mhandle);
  466. }
  467. }
  468. public override string Name {
  469. get {
  470. if (name != null)
  471. return name;
  472. return MonoMethod.get_name (this);
  473. }
  474. }
  475. public override bool IsDefined (Type attributeType, bool inherit) {
  476. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  477. }
  478. public override object[] GetCustomAttributes( bool inherit) {
  479. return MonoCustomAttrs.GetCustomAttributes (this, inherit);
  480. }
  481. public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
  482. return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
  483. }
  484. public override MethodBody GetMethodBody () {
  485. return GetMethodBody (mhandle);
  486. }
  487. public override string ToString () {
  488. StringBuilder sb = new StringBuilder ();
  489. sb.Append ("Void ");
  490. sb.Append (Name);
  491. sb.Append ("(");
  492. ParameterInfo[] p = GetParameters ();
  493. for (int i = 0; i < p.Length; ++i) {
  494. if (i > 0)
  495. sb.Append (", ");
  496. sb.Append (p[i].ParameterType.Name);
  497. }
  498. if (CallingConvention == CallingConventions.Any)
  499. sb.Append (", ...");
  500. sb.Append (")");
  501. return sb.ToString ();
  502. }
  503. // ISerializable
  504. public void GetObjectData(SerializationInfo info, StreamingContext context)
  505. {
  506. MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Constructor);
  507. }
  508. #if NET_4_0
  509. public override IList<CustomAttributeData> GetCustomAttributesData () {
  510. return CustomAttributeData.GetCustomAttributes (this);
  511. }
  512. #endif
  513. }
  514. }