MonoMethod.cs 18 KB

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