MonoMethod.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. internal override int GetParameterCount ()
  146. {
  147. var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
  148. return pi == null ? 0 : pi.Length;
  149. }
  150. /*
  151. * InternalInvoke() receives the parameters correctly converted by the
  152. * binder to match the types of the method signature.
  153. */
  154. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  155. internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
  156. public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  157. {
  158. if (binder == null)
  159. binder = Binder.DefaultBinder;
  160. /*Avoid allocating an array every time*/
  161. ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
  162. if ((parameters == null && pinfo.Length != 0) || (parameters != null && parameters.Length != pinfo.Length))
  163. throw new TargetParameterCountException ("parameters do not match signature");
  164. if ((invokeAttr & BindingFlags.ExactBinding) == 0) {
  165. if (!Binder.ConvertArgs (binder, parameters, pinfo, culture))
  166. throw new ArgumentException ("failed to convert parameters");
  167. } else {
  168. for (int i = 0; i < pinfo.Length; i++)
  169. if (parameters[i].GetType() != pinfo[i].ParameterType)
  170. throw new ArgumentException ("parameters do not match signature");
  171. }
  172. #if !NET_2_1
  173. if (SecurityManager.SecurityEnabled) {
  174. // sadly Attributes doesn't tell us which kind of security action this is so
  175. // we must do it the hard way - and it also means that we can skip calling
  176. // Attribute (which is another an icall)
  177. SecurityManager.ReflectedLinkDemandInvoke (this);
  178. }
  179. #endif
  180. if (ContainsGenericParameters)
  181. throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.");
  182. Exception exc;
  183. object o = null;
  184. try {
  185. // The ex argument is used to distinguish exceptions thrown by the icall
  186. // from the exceptions thrown by the called method (which need to be
  187. // wrapped in TargetInvocationException).
  188. o = InternalInvoke (obj, parameters, out exc);
  189. } catch (ThreadAbortException) {
  190. throw;
  191. #if NET_2_1
  192. } catch (MethodAccessException) {
  193. throw;
  194. #endif
  195. } catch (Exception e) {
  196. throw new TargetInvocationException (e);
  197. }
  198. if (exc != null)
  199. throw exc;
  200. return o;
  201. }
  202. public override RuntimeMethodHandle MethodHandle {
  203. get {return new RuntimeMethodHandle (mhandle);}
  204. }
  205. public override MethodAttributes Attributes {
  206. get {
  207. return MonoMethodInfo.GetAttributes (mhandle);
  208. }
  209. }
  210. public override CallingConventions CallingConvention {
  211. get {
  212. return MonoMethodInfo.GetCallingConvention (mhandle);
  213. }
  214. }
  215. public override Type ReflectedType {
  216. get {
  217. return reftype;
  218. }
  219. }
  220. public override Type DeclaringType {
  221. get {
  222. return MonoMethodInfo.GetDeclaringType (mhandle);
  223. }
  224. }
  225. public override string Name {
  226. get {
  227. if (name != null)
  228. return name;
  229. return get_name (this);
  230. }
  231. }
  232. public override bool IsDefined (Type attributeType, bool inherit) {
  233. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  234. }
  235. public override object[] GetCustomAttributes( bool inherit) {
  236. return MonoCustomAttrs.GetCustomAttributes (this, inherit);
  237. }
  238. public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
  239. return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
  240. }
  241. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  242. internal static extern DllImportAttribute GetDllImportAttribute (IntPtr mhandle);
  243. internal object[] GetPseudoCustomAttributes ()
  244. {
  245. int count = 0;
  246. /* MS.NET doesn't report MethodImplAttribute */
  247. MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
  248. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  249. count ++;
  250. if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
  251. count ++;
  252. if (count == 0)
  253. return null;
  254. object[] attrs = new object [count];
  255. count = 0;
  256. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  257. attrs [count ++] = new PreserveSigAttribute ();
  258. if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) {
  259. DllImportAttribute attr = GetDllImportAttribute (mhandle);
  260. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  261. attr.PreserveSig = true;
  262. attrs [count ++] = attr;
  263. }
  264. return attrs;
  265. }
  266. static bool ShouldPrintFullName (Type type) {
  267. return type.IsClass && (!type.IsPointer ||
  268. (!type.GetElementType ().IsPrimitive && !type.GetElementType ().IsNested));
  269. }
  270. public override string ToString () {
  271. StringBuilder sb = new StringBuilder ();
  272. Type retType = ReturnType;
  273. if (ShouldPrintFullName (retType))
  274. sb.Append (retType.ToString ());
  275. else
  276. sb.Append (retType.Name);
  277. sb.Append (" ");
  278. sb.Append (Name);
  279. if (IsGenericMethod) {
  280. Type[] gen_params = GetGenericArguments ();
  281. sb.Append ("[");
  282. for (int j = 0; j < gen_params.Length; j++) {
  283. if (j > 0)
  284. sb.Append (",");
  285. sb.Append (gen_params [j].Name);
  286. }
  287. sb.Append ("]");
  288. }
  289. sb.Append ("(");
  290. ParameterInfo[] p = GetParameters ();
  291. for (int i = 0; i < p.Length; ++i) {
  292. if (i > 0)
  293. sb.Append (", ");
  294. Type pt = p[i].ParameterType;
  295. bool byref = pt.IsByRef;
  296. if (byref)
  297. pt = pt.GetElementType ();
  298. if (ShouldPrintFullName (pt))
  299. sb.Append (pt.ToString ());
  300. else
  301. sb.Append (pt.Name);
  302. if (byref)
  303. sb.Append (" ByRef");
  304. }
  305. if ((CallingConvention & CallingConventions.VarArgs) != 0) {
  306. if (p.Length > 0)
  307. sb.Append (", ");
  308. sb.Append ("...");
  309. }
  310. sb.Append (")");
  311. return sb.ToString ();
  312. }
  313. // ISerializable
  314. public void GetObjectData(SerializationInfo info, StreamingContext context)
  315. {
  316. Type[] genericArguments = IsGenericMethod && !IsGenericMethodDefinition
  317. ? GetGenericArguments () : null;
  318. MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Method, genericArguments);
  319. }
  320. public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
  321. {
  322. if (methodInstantiation == null)
  323. throw new ArgumentNullException ("methodInstantiation");
  324. if (!IsGenericMethodDefinition)
  325. throw new InvalidOperationException ("not a generic method definition");
  326. /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
  327. if (GetGenericArguments ().Length != methodInstantiation.Length)
  328. throw new ArgumentException ("Incorrect length");
  329. bool hasUserType = false;
  330. foreach (Type type in methodInstantiation) {
  331. if (type == null)
  332. throw new ArgumentNullException ();
  333. if (!(type is MonoType))
  334. hasUserType = true;
  335. }
  336. if (hasUserType)
  337. return new MethodOnTypeBuilderInst (this, methodInstantiation);
  338. MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
  339. if (ret == null)
  340. throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
  341. return ret;
  342. }
  343. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  344. extern MethodInfo MakeGenericMethod_impl (Type [] types);
  345. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  346. public override extern Type [] GetGenericArguments ();
  347. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  348. extern MethodInfo GetGenericMethodDefinition_impl ();
  349. public override MethodInfo GetGenericMethodDefinition ()
  350. {
  351. MethodInfo res = GetGenericMethodDefinition_impl ();
  352. if (res == null)
  353. throw new InvalidOperationException ();
  354. return res;
  355. }
  356. public override extern bool IsGenericMethodDefinition {
  357. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  358. get;
  359. }
  360. public override extern bool IsGenericMethod {
  361. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  362. get;
  363. }
  364. public override bool ContainsGenericParameters {
  365. get {
  366. if (IsGenericMethod) {
  367. foreach (Type arg in GetGenericArguments ())
  368. if (arg.ContainsGenericParameters)
  369. return true;
  370. }
  371. return DeclaringType.ContainsGenericParameters;
  372. }
  373. }
  374. public override MethodBody GetMethodBody () {
  375. return GetMethodBody (mhandle);
  376. }
  377. #if NET_4_0
  378. public override IList<CustomAttributeData> GetCustomAttributesData () {
  379. return CustomAttributeData.GetCustomAttributes (this);
  380. }
  381. #endif
  382. }
  383. internal class MonoCMethod : ConstructorInfo, ISerializable
  384. {
  385. #pragma warning disable 649
  386. internal IntPtr mhandle;
  387. string name;
  388. Type reftype;
  389. #pragma warning restore 649
  390. public override MethodImplAttributes GetMethodImplementationFlags ()
  391. {
  392. return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
  393. }
  394. public override ParameterInfo[] GetParameters ()
  395. {
  396. return MonoMethodInfo.GetParametersInfo (mhandle, this);
  397. }
  398. internal override int GetParameterCount ()
  399. {
  400. var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
  401. return pi == null ? 0 : pi.Length;
  402. }
  403. /*
  404. * InternalInvoke() receives the parameters corretcly converted by the binder
  405. * to match the types of the method signature.
  406. */
  407. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  408. internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
  409. public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  410. {
  411. if (binder == null)
  412. binder = Binder.DefaultBinder;
  413. ParameterInfo[] pinfo = GetParameters ();
  414. if ((parameters == null && pinfo.Length != 0) || (parameters != null && parameters.Length != pinfo.Length))
  415. throw new TargetParameterCountException ("parameters do not match signature");
  416. if ((invokeAttr & BindingFlags.ExactBinding) == 0) {
  417. if (!Binder.ConvertArgs (binder, parameters, pinfo, culture))
  418. throw new ArgumentException ("failed to convert parameters");
  419. } else {
  420. for (int i = 0; i < pinfo.Length; i++)
  421. if (parameters[i].GetType() != pinfo[i].ParameterType)
  422. throw new ArgumentException ("parameters do not match signature");
  423. }
  424. #if !NET_2_1
  425. if (SecurityManager.SecurityEnabled) {
  426. // sadly Attributes doesn't tell us which kind of security action this is so
  427. // we must do it the hard way - and it also means that we can skip calling
  428. // Attribute (which is another an icall)
  429. SecurityManager.ReflectedLinkDemandInvoke (this);
  430. }
  431. #endif
  432. if (obj == null && DeclaringType.ContainsGenericParameters)
  433. throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
  434. if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) {
  435. throw new MemberAccessException (String.Format ("Cannot create an instance of {0} because it is an abstract class", DeclaringType));
  436. }
  437. Exception exc = null;
  438. object o = null;
  439. try {
  440. o = InternalInvoke (obj, parameters, out exc);
  441. #if NET_2_1
  442. } catch (MethodAccessException) {
  443. throw;
  444. #endif
  445. } catch (Exception e) {
  446. throw new TargetInvocationException (e);
  447. }
  448. if (exc != null)
  449. throw exc;
  450. return (obj == null) ? o : null;
  451. }
  452. public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
  453. return Invoke (null, invokeAttr, binder, parameters, culture);
  454. }
  455. public override RuntimeMethodHandle MethodHandle {
  456. get {return new RuntimeMethodHandle (mhandle);}
  457. }
  458. public override MethodAttributes Attributes {
  459. get {
  460. return MonoMethodInfo.GetAttributes (mhandle);
  461. }
  462. }
  463. public override CallingConventions CallingConvention {
  464. get {
  465. return MonoMethodInfo.GetCallingConvention (mhandle);
  466. }
  467. }
  468. public override Type ReflectedType {
  469. get {
  470. return reftype;
  471. }
  472. }
  473. public override Type DeclaringType {
  474. get {
  475. return MonoMethodInfo.GetDeclaringType (mhandle);
  476. }
  477. }
  478. public override string Name {
  479. get {
  480. if (name != null)
  481. return name;
  482. return MonoMethod.get_name (this);
  483. }
  484. }
  485. public override bool IsDefined (Type attributeType, bool inherit) {
  486. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  487. }
  488. public override object[] GetCustomAttributes( bool inherit) {
  489. return MonoCustomAttrs.GetCustomAttributes (this, inherit);
  490. }
  491. public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
  492. return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
  493. }
  494. public override MethodBody GetMethodBody () {
  495. return GetMethodBody (mhandle);
  496. }
  497. public override string ToString () {
  498. StringBuilder sb = new StringBuilder ();
  499. sb.Append ("Void ");
  500. sb.Append (Name);
  501. sb.Append ("(");
  502. ParameterInfo[] p = GetParameters ();
  503. for (int i = 0; i < p.Length; ++i) {
  504. if (i > 0)
  505. sb.Append (", ");
  506. sb.Append (p[i].ParameterType.Name);
  507. }
  508. if (CallingConvention == CallingConventions.Any)
  509. sb.Append (", ...");
  510. sb.Append (")");
  511. return sb.ToString ();
  512. }
  513. // ISerializable
  514. public void GetObjectData(SerializationInfo info, StreamingContext context)
  515. {
  516. MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Constructor);
  517. }
  518. #if NET_4_0
  519. public override IList<CustomAttributeData> GetCustomAttributesData () {
  520. return CustomAttributeData.GetCustomAttributes (this);
  521. }
  522. #endif
  523. }
  524. }