MonoMethod.cs 17 KB

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