RuntimeMethodInfo.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. //
  2. // RuntimeMethodInfo.cs: The class used to represent methods from the mono runtime.
  3. //
  4. // Authors:
  5. // Paolo Molaro ([email protected])
  6. // Marek Safar ([email protected])
  7. //
  8. // (C) 2001 Ximian, Inc. http://www.ximian.com
  9. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  10. // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Collections.Generic;
  33. using System.Globalization;
  34. using System.Runtime.CompilerServices;
  35. using System.Runtime.InteropServices;
  36. using InteropServicesCallingConvention = System.Runtime.InteropServices.CallingConvention;
  37. using System.Runtime.Serialization;
  38. #if !FULL_AOT_RUNTIME
  39. using System.Reflection.Emit;
  40. #endif
  41. using System.Security;
  42. using System.Threading;
  43. using System.Text;
  44. using System.Diagnostics;
  45. namespace System.Reflection {
  46. #if NETCORE
  47. [Flags()]
  48. internal enum PInvokeAttributes
  49. {
  50. NoMangle = 0x0001,
  51. CharSetMask = 0x0006,
  52. CharSetNotSpec = 0x0000,
  53. CharSetAnsi = 0x0002,
  54. CharSetUnicode = 0x0004,
  55. CharSetAuto = 0x0006,
  56. BestFitUseAssem = 0x0000,
  57. BestFitEnabled = 0x0010,
  58. BestFitDisabled = 0x0020,
  59. BestFitMask = 0x0030,
  60. ThrowOnUnmappableCharUseAssem = 0x0000,
  61. ThrowOnUnmappableCharEnabled = 0x1000,
  62. ThrowOnUnmappableCharDisabled = 0x2000,
  63. ThrowOnUnmappableCharMask = 0x3000,
  64. SupportsLastError = 0x0040,
  65. CallConvMask = 0x0700,
  66. CallConvWinapi = 0x0100,
  67. CallConvCdecl = 0x0200,
  68. CallConvStdcall = 0x0300,
  69. CallConvThiscall = 0x0400,
  70. CallConvFastcall = 0x0500,
  71. MaxValue = 0xFFFF,
  72. }
  73. #endif
  74. internal struct MonoMethodInfo
  75. {
  76. #pragma warning disable 649
  77. private Type parent;
  78. private Type ret;
  79. internal MethodAttributes attrs;
  80. internal MethodImplAttributes iattrs;
  81. private CallingConventions callconv;
  82. #pragma warning restore 649
  83. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  84. static extern void get_method_info (IntPtr handle, out MonoMethodInfo info);
  85. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  86. static extern int get_method_attributes (IntPtr handle);
  87. internal static MonoMethodInfo GetMethodInfo (IntPtr handle)
  88. {
  89. MonoMethodInfo info;
  90. MonoMethodInfo.get_method_info (handle, out info);
  91. return info;
  92. }
  93. internal static Type GetDeclaringType (IntPtr handle)
  94. {
  95. return GetMethodInfo (handle).parent;
  96. }
  97. internal static Type GetReturnType (IntPtr handle)
  98. {
  99. return GetMethodInfo (handle).ret;
  100. }
  101. internal static MethodAttributes GetAttributes (IntPtr handle)
  102. {
  103. return (MethodAttributes)get_method_attributes (handle);
  104. }
  105. internal static CallingConventions GetCallingConvention (IntPtr handle)
  106. {
  107. return GetMethodInfo (handle).callconv;
  108. }
  109. internal static MethodImplAttributes GetMethodImplementationFlags (IntPtr handle)
  110. {
  111. return GetMethodInfo (handle).iattrs;
  112. }
  113. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  114. static extern ParameterInfo[] get_parameter_info (IntPtr handle, MemberInfo member);
  115. static internal ParameterInfo[] GetParametersInfo (IntPtr handle, MemberInfo member)
  116. {
  117. return get_parameter_info (handle, member);
  118. }
  119. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  120. static extern MarshalAsAttribute get_retval_marshal (IntPtr handle);
  121. static internal ParameterInfo GetReturnParameterInfo (RuntimeMethodInfo method)
  122. {
  123. return RuntimeParameterInfo.New (GetReturnType (method.mhandle), method, get_retval_marshal (method.mhandle));
  124. }
  125. }
  126. /*
  127. * Note: most of this class needs to be duplicated for the contructor, since
  128. * the .NET reflection class hierarchy is so broken.
  129. */
  130. [Serializable()]
  131. [StructLayout (LayoutKind.Sequential)]
  132. class RuntimeMethodInfo : MethodInfo
  133. #if !NETCORE
  134. , ISerializable
  135. #endif
  136. {
  137. #pragma warning disable 649
  138. internal IntPtr mhandle;
  139. string name;
  140. Type reftype;
  141. #pragma warning restore 649
  142. internal BindingFlags BindingFlags {
  143. get {
  144. return 0;
  145. }
  146. }
  147. public override Module Module {
  148. get {
  149. return GetRuntimeModule ();
  150. }
  151. }
  152. RuntimeType ReflectedTypeInternal {
  153. get {
  154. return (RuntimeType) ReflectedType;
  155. }
  156. }
  157. #if NETCORE
  158. string FormatNameAndSig (bool serialization)
  159. #else
  160. internal override string FormatNameAndSig (bool serialization)
  161. #endif
  162. {
  163. // Serialization uses ToString to resolve MethodInfo overloads.
  164. StringBuilder sbName = new StringBuilder(Name);
  165. // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads.
  166. // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString().
  167. TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic;
  168. if (IsGenericMethod)
  169. sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format));
  170. sbName.Append("(");
  171. RuntimeParameterInfo.FormatParameters (sbName, GetParametersNoCopy (), CallingConvention, serialization);
  172. sbName.Append(")");
  173. return sbName.ToString();
  174. }
  175. public override Delegate CreateDelegate (Type delegateType)
  176. {
  177. return Delegate.CreateDelegate (delegateType, this);
  178. }
  179. public override Delegate CreateDelegate (Type delegateType, object target)
  180. {
  181. return Delegate.CreateDelegate (delegateType, target, this);
  182. }
  183. public override String ToString()
  184. {
  185. return ReturnType.FormatTypeName() + " " + FormatNameAndSig(false);
  186. }
  187. internal RuntimeModule GetRuntimeModule ()
  188. {
  189. return ((RuntimeType)DeclaringType).GetRuntimeModule();
  190. }
  191. #if !NETCORE
  192. #region ISerializable Implementation
  193. public void GetObjectData(SerializationInfo info, StreamingContext context)
  194. {
  195. if (info == null)
  196. throw new ArgumentNullException("info");
  197. MemberInfoSerializationHolder.GetSerializationInfo(
  198. info,
  199. Name,
  200. ReflectedTypeInternal,
  201. ToString(),
  202. SerializationToString(),
  203. MemberTypes.Method,
  204. IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null);
  205. }
  206. internal string SerializationToString()
  207. {
  208. return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true);
  209. }
  210. #endregion
  211. #endif
  212. internal static MethodBase GetMethodFromHandleNoGenericCheck (RuntimeMethodHandle handle)
  213. {
  214. return GetMethodFromHandleInternalType_native (handle.Value, IntPtr.Zero, false);
  215. }
  216. internal static MethodBase GetMethodFromHandleNoGenericCheck (RuntimeMethodHandle handle, RuntimeTypeHandle reflectedType)
  217. {
  218. return GetMethodFromHandleInternalType_native (handle.Value, reflectedType.Value, false);
  219. }
  220. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  221. [PreserveDependency(".ctor(System.Reflection.ExceptionHandlingClause[],System.Reflection.LocalVariableInfo[],System.Byte[],System.Boolean,System.Int32,System.Int32)", "System.Reflection.MethodBody")]
  222. internal extern static MethodBody GetMethodBodyInternal (IntPtr handle);
  223. internal static MethodBody GetMethodBody (IntPtr handle)
  224. {
  225. return GetMethodBodyInternal (handle);
  226. }
  227. internal static MethodBase GetMethodFromHandleInternalType (IntPtr method_handle, IntPtr type_handle) {
  228. return GetMethodFromHandleInternalType_native (method_handle, type_handle, true);
  229. }
  230. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  231. extern static MethodBase GetMethodFromHandleInternalType_native (IntPtr method_handle, IntPtr type_handle, bool genericCheck);
  232. internal RuntimeMethodInfo () {
  233. }
  234. internal RuntimeMethodInfo (RuntimeMethodHandle mhandle) {
  235. this.mhandle = mhandle.Value;
  236. }
  237. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  238. internal static extern string get_name (MethodBase method);
  239. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  240. internal static extern RuntimeMethodInfo get_base_method (RuntimeMethodInfo method, bool definition);
  241. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  242. internal static extern int get_metadata_token (RuntimeMethodInfo method);
  243. public override MethodInfo GetBaseDefinition ()
  244. {
  245. return get_base_method (this, true);
  246. }
  247. // TODO: Remove, needed only for MonoCustomAttribute
  248. internal MethodInfo GetBaseMethod ()
  249. {
  250. return get_base_method (this, false);
  251. }
  252. public override ParameterInfo ReturnParameter {
  253. get {
  254. return MonoMethodInfo.GetReturnParameterInfo (this);
  255. }
  256. }
  257. public override Type ReturnType {
  258. get {
  259. return MonoMethodInfo.GetReturnType (mhandle);
  260. }
  261. }
  262. public override ICustomAttributeProvider ReturnTypeCustomAttributes {
  263. get {
  264. return MonoMethodInfo.GetReturnParameterInfo (this);
  265. }
  266. }
  267. public override int MetadataToken {
  268. get {
  269. return get_metadata_token (this);
  270. }
  271. }
  272. public override MethodImplAttributes GetMethodImplementationFlags ()
  273. {
  274. return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
  275. }
  276. public override ParameterInfo[] GetParameters ()
  277. {
  278. var src = MonoMethodInfo.GetParametersInfo (mhandle, this);
  279. if (src.Length == 0)
  280. return src;
  281. // Have to clone because GetParametersInfo icall returns cached value
  282. var dest = new ParameterInfo [src.Length];
  283. Array.FastCopy (src, 0, dest, 0, src.Length);
  284. return dest;
  285. }
  286. internal override ParameterInfo[] GetParametersInternal ()
  287. {
  288. return MonoMethodInfo.GetParametersInfo (mhandle, this);
  289. }
  290. internal override int GetParametersCount ()
  291. {
  292. return MonoMethodInfo.GetParametersInfo (mhandle, this).Length;
  293. }
  294. /*
  295. * InternalInvoke() receives the parameters correctly converted by the
  296. * binder to match the types of the method signature.
  297. * The exc argument is used to capture exceptions thrown by the icall.
  298. * Exceptions thrown by the called method propagate normally.
  299. */
  300. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  301. internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
  302. [DebuggerHidden]
  303. [DebuggerStepThrough]
  304. public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  305. {
  306. if (!IsStatic) {
  307. if (!DeclaringType.IsInstanceOfType (obj)) {
  308. if (obj == null)
  309. throw new TargetException ("Non-static method requires a target.");
  310. else
  311. throw new TargetException ("Object does not match target type.");
  312. }
  313. }
  314. if (binder == null)
  315. binder = Type.DefaultBinder;
  316. /*Avoid allocating an array every time*/
  317. ParameterInfo[] pinfo = GetParametersInternal ();
  318. ConvertValues (binder, parameters, pinfo, culture, invokeAttr);
  319. if (ContainsGenericParameters)
  320. throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.");
  321. Exception exc;
  322. object o = null;
  323. if ((invokeAttr & BindingFlags.DoNotWrapExceptions) == 0) {
  324. try {
  325. o = InternalInvoke (obj, parameters, out exc);
  326. } catch (ThreadAbortException) {
  327. throw;
  328. #if MOBILE
  329. } catch (MethodAccessException) {
  330. throw;
  331. #endif
  332. } catch (OverflowException) {
  333. throw;
  334. } catch (Exception e) {
  335. throw new TargetInvocationException (e);
  336. }
  337. }
  338. else
  339. {
  340. o = InternalInvoke (obj, parameters, out exc);
  341. }
  342. if (exc != null)
  343. throw exc;
  344. return o;
  345. }
  346. internal static void ConvertValues (Binder binder, object[] args, ParameterInfo[] pinfo, CultureInfo culture, BindingFlags invokeAttr)
  347. {
  348. if (args == null) {
  349. if (pinfo.Length == 0)
  350. return;
  351. throw new TargetParameterCountException ();
  352. }
  353. if (pinfo.Length != args.Length)
  354. throw new TargetParameterCountException ();
  355. for (int i = 0; i < args.Length; ++i) {
  356. var arg = args [i];
  357. var pi = pinfo [i];
  358. if (arg == Type.Missing) {
  359. if (pi.DefaultValue == System.DBNull.Value)
  360. throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),"parameters");
  361. args [i] = pi.DefaultValue;
  362. continue;
  363. }
  364. var rt = (RuntimeType) pi.ParameterType;
  365. args [i] = rt.CheckValue (arg, binder, culture, invokeAttr);
  366. }
  367. }
  368. public override RuntimeMethodHandle MethodHandle {
  369. get {
  370. return new RuntimeMethodHandle (mhandle);
  371. }
  372. }
  373. public override MethodAttributes Attributes {
  374. get {
  375. return MonoMethodInfo.GetAttributes (mhandle);
  376. }
  377. }
  378. public override CallingConventions CallingConvention {
  379. get {
  380. return MonoMethodInfo.GetCallingConvention (mhandle);
  381. }
  382. }
  383. public override Type ReflectedType {
  384. get {
  385. return reftype;
  386. }
  387. }
  388. public override Type DeclaringType {
  389. get {
  390. return MonoMethodInfo.GetDeclaringType (mhandle);
  391. }
  392. }
  393. public override string Name {
  394. get {
  395. if (name != null)
  396. return name;
  397. return get_name (this);
  398. }
  399. }
  400. public override bool IsDefined (Type attributeType, bool inherit) {
  401. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  402. }
  403. public override object[] GetCustomAttributes( bool inherit) {
  404. return MonoCustomAttrs.GetCustomAttributes (this, inherit);
  405. }
  406. public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
  407. return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
  408. }
  409. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  410. internal extern void GetPInvoke (out PInvokeAttributes flags, out string entryPoint, out string dllName);
  411. internal object[] GetPseudoCustomAttributes ()
  412. {
  413. int count = 0;
  414. /* MS.NET doesn't report MethodImplAttribute */
  415. MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
  416. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  417. count ++;
  418. if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
  419. count ++;
  420. if (count == 0)
  421. return null;
  422. object[] attrs = new object [count];
  423. count = 0;
  424. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  425. attrs [count ++] = new PreserveSigAttribute ();
  426. if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) {
  427. #if NETCORE
  428. throw new NotImplementedException ();
  429. #else
  430. attrs [count ++] = DllImportAttribute.GetCustomAttribute (this);
  431. #endif
  432. }
  433. return attrs;
  434. }
  435. internal CustomAttributeData[] GetPseudoCustomAttributesData ()
  436. {
  437. int count = 0;
  438. /* MS.NET doesn't report MethodImplAttribute */
  439. MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
  440. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  441. count++;
  442. if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
  443. count++;
  444. if (count == 0)
  445. return null;
  446. CustomAttributeData[] attrsData = new CustomAttributeData [count];
  447. count = 0;
  448. if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
  449. attrsData [count++] = new CustomAttributeData ((typeof (PreserveSigAttribute)).GetConstructor (Type.EmptyTypes));
  450. if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
  451. attrsData [count++] = GetDllImportAttributeData ();
  452. return attrsData;
  453. }
  454. private CustomAttributeData GetDllImportAttributeData ()
  455. {
  456. if ((Attributes & MethodAttributes.PinvokeImpl) == 0)
  457. return null;
  458. string entryPoint, dllName = null;
  459. PInvokeAttributes flags = 0;
  460. GetPInvoke (out flags, out entryPoint, out dllName);
  461. CharSet charSet;
  462. switch (flags & PInvokeAttributes.CharSetMask) {
  463. case PInvokeAttributes.CharSetNotSpec:
  464. charSet = CharSet.None;
  465. break;
  466. case PInvokeAttributes.CharSetAnsi:
  467. charSet = CharSet.Ansi;
  468. break;
  469. case PInvokeAttributes.CharSetUnicode:
  470. charSet = CharSet.Unicode;
  471. break;
  472. case PInvokeAttributes.CharSetAuto:
  473. charSet = CharSet.Auto;
  474. break;
  475. // Invalid: default to CharSet.None
  476. default:
  477. charSet = CharSet.None;
  478. break;
  479. }
  480. InteropServicesCallingConvention callingConvention;
  481. switch (flags & PInvokeAttributes.CallConvMask) {
  482. case PInvokeAttributes.CallConvWinapi:
  483. callingConvention = InteropServicesCallingConvention.Winapi;
  484. break;
  485. case PInvokeAttributes.CallConvCdecl:
  486. callingConvention = InteropServicesCallingConvention.Cdecl;
  487. break;
  488. case PInvokeAttributes.CallConvStdcall:
  489. callingConvention = InteropServicesCallingConvention.StdCall;
  490. break;
  491. case PInvokeAttributes.CallConvThiscall:
  492. callingConvention = InteropServicesCallingConvention.ThisCall;
  493. break;
  494. case PInvokeAttributes.CallConvFastcall:
  495. callingConvention = InteropServicesCallingConvention.FastCall;
  496. break;
  497. // Invalid: default to CallingConvention.Cdecl
  498. default:
  499. callingConvention = InteropServicesCallingConvention.Cdecl;
  500. break;
  501. }
  502. bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0;
  503. bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0;
  504. bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled;
  505. bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled;
  506. bool preserveSig = (GetMethodImplementationFlags () & MethodImplAttributes.PreserveSig) != 0;
  507. var ctorArgs = new CustomAttributeTypedArgument [] {
  508. new CustomAttributeTypedArgument (typeof (string), dllName),
  509. };
  510. var attrType = typeof (DllImportAttribute);
  511. var namedArgs = new CustomAttributeNamedArgument [] {
  512. new CustomAttributeNamedArgument (attrType.GetField ("EntryPoint"), entryPoint),
  513. new CustomAttributeNamedArgument (attrType.GetField ("CharSet"), charSet),
  514. new CustomAttributeNamedArgument (attrType.GetField ("ExactSpelling"), exactSpelling),
  515. new CustomAttributeNamedArgument (attrType.GetField ("SetLastError"), setLastError),
  516. new CustomAttributeNamedArgument (attrType.GetField ("PreserveSig"), preserveSig),
  517. new CustomAttributeNamedArgument (attrType.GetField ("CallingConvention"), callingConvention),
  518. new CustomAttributeNamedArgument (attrType.GetField ("BestFitMapping"), bestFitMapping),
  519. new CustomAttributeNamedArgument (attrType.GetField ("ThrowOnUnmappableChar"), throwOnUnmappableChar)
  520. };
  521. return new CustomAttributeData (
  522. attrType.GetConstructor (new[] { typeof (string) }),
  523. ctorArgs,
  524. namedArgs);
  525. }
  526. public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
  527. {
  528. if (methodInstantiation == null)
  529. throw new ArgumentNullException ("methodInstantiation");
  530. if (!IsGenericMethodDefinition)
  531. throw new InvalidOperationException ("not a generic method definition");
  532. /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
  533. if (GetGenericArguments ().Length != methodInstantiation.Length)
  534. throw new ArgumentException ("Incorrect length");
  535. bool hasUserType = false;
  536. foreach (Type type in methodInstantiation) {
  537. if (type == null)
  538. throw new ArgumentNullException ();
  539. if (!(type is RuntimeType))
  540. hasUserType = true;
  541. }
  542. if (hasUserType) {
  543. #if FULL_AOT_RUNTIME
  544. throw new NotSupportedException ("User types are not supported under full aot");
  545. #elif NETCORE
  546. throw new NotImplementedException ();
  547. #else
  548. return new MethodOnTypeBuilderInst (this, methodInstantiation);
  549. #endif
  550. }
  551. MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
  552. if (ret == null)
  553. throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
  554. return ret;
  555. }
  556. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  557. extern MethodInfo MakeGenericMethod_impl (Type [] types);
  558. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  559. public override extern Type [] GetGenericArguments ();
  560. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  561. extern MethodInfo GetGenericMethodDefinition_impl ();
  562. public override MethodInfo GetGenericMethodDefinition ()
  563. {
  564. MethodInfo res = GetGenericMethodDefinition_impl ();
  565. if (res == null)
  566. throw new InvalidOperationException ();
  567. return res;
  568. }
  569. public override extern bool IsGenericMethodDefinition {
  570. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  571. get;
  572. }
  573. public override extern bool IsGenericMethod {
  574. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  575. get;
  576. }
  577. public override bool ContainsGenericParameters {
  578. get {
  579. if (IsGenericMethod) {
  580. foreach (Type arg in GetGenericArguments ())
  581. if (arg.ContainsGenericParameters)
  582. return true;
  583. }
  584. return DeclaringType.ContainsGenericParameters;
  585. }
  586. }
  587. public override MethodBody GetMethodBody () {
  588. #if NETCORE
  589. throw new NotImplementedException ();
  590. #else
  591. return GetMethodBody (mhandle);
  592. #endif
  593. }
  594. public override IList<CustomAttributeData> GetCustomAttributesData () {
  595. return CustomAttributeData.GetCustomAttributes (this);
  596. }
  597. #if MOBILE
  598. static int get_core_clr_security_level ()
  599. {
  600. return 1;
  601. }
  602. #else
  603. //seclevel { transparent = 0, safe-critical = 1, critical = 2}
  604. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  605. public extern int get_core_clr_security_level ();
  606. #endif
  607. public override bool IsSecurityTransparent {
  608. get { return get_core_clr_security_level () == 0; }
  609. }
  610. public override bool IsSecurityCritical {
  611. get { return get_core_clr_security_level () > 0; }
  612. }
  613. public override bool IsSecuritySafeCritical {
  614. get { return get_core_clr_security_level () == 1; }
  615. }
  616. #if !NETCORE
  617. public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeMethodInfo> (other);
  618. #endif
  619. }
  620. [Serializable()]
  621. [StructLayout (LayoutKind.Sequential)]
  622. class RuntimeConstructorInfo : ConstructorInfo, ISerializable
  623. {
  624. #pragma warning disable 649
  625. internal IntPtr mhandle;
  626. string name;
  627. Type reftype;
  628. #pragma warning restore 649
  629. public override Module Module {
  630. get {
  631. return GetRuntimeModule ();
  632. }
  633. }
  634. internal RuntimeModule GetRuntimeModule ()
  635. {
  636. return RuntimeTypeHandle.GetModule((RuntimeType)DeclaringType);
  637. }
  638. internal BindingFlags BindingFlags {
  639. get {
  640. return 0;
  641. }
  642. }
  643. RuntimeType ReflectedTypeInternal {
  644. get {
  645. return (RuntimeType) ReflectedType;
  646. }
  647. }
  648. #region ISerializable Implementation
  649. public void GetObjectData(SerializationInfo info, StreamingContext context)
  650. {
  651. if (info == null)
  652. throw new ArgumentNullException("info");
  653. #if NETCORE
  654. throw new NotImplementedException ();
  655. #else
  656. MemberInfoSerializationHolder.GetSerializationInfo(
  657. info,
  658. Name,
  659. ReflectedTypeInternal,
  660. ToString(),
  661. SerializationToString(),
  662. MemberTypes.Constructor,
  663. null);
  664. #endif
  665. }
  666. internal string SerializationToString()
  667. {
  668. #if NETCORE
  669. throw new NotImplementedException ();
  670. #else
  671. // We don't need the return type for constructors.
  672. return FormatNameAndSig(true);
  673. #endif
  674. }
  675. internal void SerializationInvoke (Object target, SerializationInfo info, StreamingContext context)
  676. {
  677. Invoke (target, new object[] { info, context });
  678. }
  679. #endregion
  680. public override MethodImplAttributes GetMethodImplementationFlags ()
  681. {
  682. return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
  683. }
  684. public override ParameterInfo[] GetParameters ()
  685. {
  686. return MonoMethodInfo.GetParametersInfo (mhandle, this);
  687. }
  688. internal override ParameterInfo[] GetParametersInternal ()
  689. {
  690. return MonoMethodInfo.GetParametersInfo (mhandle, this);
  691. }
  692. internal override int GetParametersCount ()
  693. {
  694. var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
  695. return pi == null ? 0 : pi.Length;
  696. }
  697. /*
  698. * InternalInvoke() receives the parameters correctly converted by the binder
  699. * to match the types of the method signature.
  700. */
  701. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  702. internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
  703. [DebuggerHidden]
  704. [DebuggerStepThrough]
  705. public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
  706. {
  707. if (obj == null) {
  708. if (!IsStatic)
  709. throw new TargetException ("Instance constructor requires a target");
  710. } else if (!DeclaringType.IsInstanceOfType (obj)) {
  711. throw new TargetException ("Constructor does not match target type");
  712. }
  713. return DoInvoke (obj, invokeAttr, binder, parameters, culture);
  714. }
  715. object DoInvoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
  716. {
  717. if (binder == null)
  718. binder = Type.DefaultBinder;
  719. ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
  720. RuntimeMethodInfo.ConvertValues (binder, parameters, pinfo, culture, invokeAttr);
  721. if (obj == null && DeclaringType.ContainsGenericParameters)
  722. throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
  723. if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) {
  724. throw new MemberAccessException (String.Format ("Cannot create an instance of {0} because it is an abstract class", DeclaringType));
  725. }
  726. return InternalInvoke (obj, parameters, (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0);
  727. }
  728. public object InternalInvoke (object obj, object[] parameters, bool wrapExceptions)
  729. {
  730. Exception exc;
  731. object o = null;
  732. if (wrapExceptions) {
  733. try {
  734. o = InternalInvoke (obj, parameters, out exc);
  735. #if MOBILE
  736. } catch (MethodAccessException) {
  737. throw;
  738. #endif
  739. } catch (OverflowException) {
  740. throw;
  741. } catch (Exception e) {
  742. throw new TargetInvocationException (e);
  743. }
  744. } else {
  745. o = InternalInvoke (obj, parameters, out exc);
  746. }
  747. if (exc != null)
  748. throw exc;
  749. return obj == null ? o : null;
  750. }
  751. [DebuggerHidden]
  752. [DebuggerStepThrough]
  753. public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  754. {
  755. return DoInvoke (null, invokeAttr, binder, parameters, culture);
  756. }
  757. public override RuntimeMethodHandle MethodHandle {
  758. get {
  759. return new RuntimeMethodHandle (mhandle);
  760. }
  761. }
  762. public override MethodAttributes Attributes {
  763. get {
  764. return MonoMethodInfo.GetAttributes (mhandle);
  765. }
  766. }
  767. public override CallingConventions CallingConvention {
  768. get {
  769. return MonoMethodInfo.GetCallingConvention (mhandle);
  770. }
  771. }
  772. public override bool ContainsGenericParameters {
  773. get {
  774. return DeclaringType.ContainsGenericParameters;
  775. }
  776. }
  777. public override Type ReflectedType {
  778. get {
  779. return reftype;
  780. }
  781. }
  782. public override Type DeclaringType {
  783. get {
  784. return MonoMethodInfo.GetDeclaringType (mhandle);
  785. }
  786. }
  787. public override string Name {
  788. get {
  789. if (name != null)
  790. return name;
  791. return RuntimeMethodInfo.get_name (this);
  792. }
  793. }
  794. public override bool IsDefined (Type attributeType, bool inherit) {
  795. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  796. }
  797. public override object[] GetCustomAttributes( bool inherit) {
  798. return MonoCustomAttrs.GetCustomAttributes (this, inherit);
  799. }
  800. public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
  801. return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
  802. }
  803. public override MethodBody GetMethodBody () {
  804. return RuntimeMethodInfo.GetMethodBody (mhandle);
  805. }
  806. public override string ToString () {
  807. #if NETCORE
  808. throw new NotImplementedException ();
  809. #else
  810. return "Void " + FormatNameAndSig (false);
  811. #endif
  812. }
  813. public override IList<CustomAttributeData> GetCustomAttributesData () {
  814. return CustomAttributeData.GetCustomAttributes (this);
  815. }
  816. #if MOBILE
  817. static int get_core_clr_security_level ()
  818. {
  819. return 1;
  820. }
  821. #else
  822. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  823. public extern int get_core_clr_security_level ();
  824. #endif
  825. #if !NETCORE
  826. public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeConstructorInfo> (other);
  827. #endif
  828. public override bool IsSecurityTransparent {
  829. get { return get_core_clr_security_level () == 0; }
  830. }
  831. public override bool IsSecurityCritical {
  832. get { return get_core_clr_security_level () > 0; }
  833. }
  834. public override bool IsSecuritySafeCritical {
  835. get { return get_core_clr_security_level () == 1; }
  836. }
  837. public override int MetadataToken {
  838. get {
  839. return get_metadata_token (this);
  840. }
  841. }
  842. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  843. internal static extern int get_metadata_token (RuntimeConstructorInfo method);
  844. }
  845. }