MonoMethod.cs 17 KB

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