DynamicMethod.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. //
  2. // System.Reflection.Emit.DynamicMethod.cs
  3. //
  4. // Author:
  5. // Paolo Molaro ([email protected])
  6. // Zoltan Varga ([email protected])
  7. //
  8. // (C) 2003 Ximian, Inc. http://www.ximian.com
  9. //
  10. //
  11. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. #if MONO_FEATURE_SRE
  33. using System;
  34. using System.Reflection;
  35. using System.Reflection.Emit;
  36. using System.Globalization;
  37. using System.Runtime.CompilerServices;
  38. using System.Runtime.InteropServices;
  39. namespace System.Reflection.Emit {
  40. [ComVisible (true)]
  41. [StructLayout (LayoutKind.Sequential)]
  42. public sealed class DynamicMethod : MethodInfo {
  43. #pragma warning disable 169, 414, 649
  44. #region Sync with reflection.h
  45. private RuntimeMethodHandle mhandle;
  46. private string name;
  47. private Type returnType;
  48. private Type[] parameters;
  49. private MethodAttributes attributes;
  50. private CallingConventions callingConvention;
  51. private Module module;
  52. private bool skipVisibility;
  53. private bool init_locals = true;
  54. private ILGenerator ilgen;
  55. private int nrefs;
  56. private object[] refs;
  57. private IntPtr referenced_by;
  58. private Type owner;
  59. #endregion
  60. #pragma warning restore 169, 414, 649
  61. private Delegate deleg;
  62. private RuntimeMethodInfo method;
  63. private ParameterBuilder[] pinfo;
  64. internal bool creating;
  65. private DynamicILInfo il_info;
  66. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m) : this (name, returnType, parameterTypes, m, false) {
  67. }
  68. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner) : this (name, returnType, parameterTypes, owner, false) {
  69. }
  70. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, m, skipVisibility) {
  71. }
  72. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, skipVisibility) {
  73. }
  74. public DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) : this (name, attributes, callingConvention, returnType, parameterTypes, owner, owner.Module, skipVisibility, false) {
  75. }
  76. public DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) : this (name, attributes, callingConvention, returnType, parameterTypes, null, m, skipVisibility, false) {
  77. }
  78. public DynamicMethod (string name, Type returnType, Type[] parameterTypes) : this (name, returnType, parameterTypes, false) {
  79. }
  80. [MonoTODO ("Visibility is not restricted")]
  81. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility)
  82. : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, null, restrictedSkipVisibility, true)
  83. {
  84. }
  85. DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type [] parameterTypes, Type owner, Module m, bool skipVisibility, bool anonHosted)
  86. {
  87. if (name == null)
  88. throw new ArgumentNullException ("name");
  89. if (returnType == null)
  90. returnType = typeof (void);
  91. if ((m == null) && !anonHosted)
  92. throw new ArgumentNullException ("m");
  93. if (returnType.IsByRef)
  94. throw new ArgumentException ("Return type can't be a byref type", "returnType");
  95. if (parameterTypes != null) {
  96. for (int i = 0; i < parameterTypes.Length; ++i)
  97. if (parameterTypes [i] == null)
  98. throw new ArgumentException ("Parameter " + i + " is null", "parameterTypes");
  99. }
  100. if (owner != null && (owner.IsArray || owner.IsInterface)) {
  101. throw new ArgumentException ("Owner can't be an array or an interface.");
  102. }
  103. if (m == null)
  104. m = AnonHostModuleHolder.AnonHostModule;
  105. this.name = name;
  106. this.attributes = attributes | MethodAttributes.Static;
  107. this.callingConvention = callingConvention;
  108. this.returnType = returnType;
  109. this.parameters = parameterTypes;
  110. this.owner = owner;
  111. this.module = m;
  112. this.skipVisibility = skipVisibility;
  113. }
  114. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  115. private static extern void create_dynamic_method (DynamicMethod m);
  116. private void CreateDynMethod () {
  117. if (mhandle.Value == IntPtr.Zero) {
  118. if (ilgen == null || ilgen.ILOffset == 0)
  119. throw new InvalidOperationException ("Method '" + name + "' does not have a method body.");
  120. ilgen.label_fixup (this);
  121. // Have to create all DynamicMethods referenced by this one
  122. try {
  123. // Used to avoid cycles
  124. creating = true;
  125. if (refs != null) {
  126. for (int i = 0; i < refs.Length; ++i) {
  127. if (refs [i] is DynamicMethod) {
  128. DynamicMethod m = (DynamicMethod)refs [i];
  129. if (!m.creating)
  130. m.CreateDynMethod ();
  131. }
  132. }
  133. }
  134. } finally {
  135. creating = false;
  136. }
  137. create_dynamic_method (this);
  138. }
  139. }
  140. [ComVisible (true)]
  141. sealed override
  142. public Delegate CreateDelegate (Type delegateType)
  143. {
  144. if (delegateType == null)
  145. throw new ArgumentNullException ("delegateType");
  146. if (deleg != null)
  147. return deleg;
  148. CreateDynMethod ();
  149. deleg = Delegate.CreateDelegate (delegateType, null, this);
  150. return deleg;
  151. }
  152. [ComVisible (true)]
  153. sealed override
  154. public Delegate CreateDelegate (Type delegateType, object target)
  155. {
  156. if (delegateType == null)
  157. throw new ArgumentNullException ("delegateType");
  158. CreateDynMethod ();
  159. /* Can't cache the delegate since it is different for each target */
  160. return Delegate.CreateDelegate (delegateType, target, this);
  161. }
  162. public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName)
  163. {
  164. //
  165. // Extension: Mono allows position == 0 for the return attribute
  166. //
  167. if ((position < 0) || (position > parameters.Length))
  168. throw new ArgumentOutOfRangeException ("position");
  169. RejectIfCreated ();
  170. ParameterBuilder pb = new ParameterBuilder (this, position, attributes, parameterName);
  171. if (pinfo == null)
  172. pinfo = new ParameterBuilder [parameters.Length + 1];
  173. pinfo [position] = pb;
  174. return pb;
  175. }
  176. public override MethodInfo GetBaseDefinition () {
  177. return this;
  178. }
  179. public override object[] GetCustomAttributes (bool inherit) {
  180. // support for MethodImplAttribute PCA
  181. return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
  182. }
  183. public override object[] GetCustomAttributes (Type attributeType,
  184. bool inherit) {
  185. if (attributeType == null)
  186. throw new ArgumentNullException ("attributeType");
  187. if (attributeType.IsAssignableFrom (typeof (MethodImplAttribute)))
  188. return new Object[] { new MethodImplAttribute (GetMethodImplementationFlags()) };
  189. else
  190. return EmptyArray<Object>.Value;
  191. }
  192. public DynamicILInfo GetDynamicILInfo () {
  193. if (il_info == null)
  194. il_info = new DynamicILInfo (this);
  195. return il_info;
  196. }
  197. public ILGenerator GetILGenerator () {
  198. return GetILGenerator (64);
  199. }
  200. public ILGenerator GetILGenerator (int streamSize) {
  201. if (((GetMethodImplementationFlags () & MethodImplAttributes.CodeTypeMask) !=
  202. MethodImplAttributes.IL) ||
  203. ((GetMethodImplementationFlags () & MethodImplAttributes.ManagedMask) !=
  204. MethodImplAttributes.Managed))
  205. throw new InvalidOperationException ("Method body should not exist.");
  206. if (ilgen != null)
  207. return ilgen;
  208. ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), streamSize);
  209. return ilgen;
  210. }
  211. public override MethodImplAttributes GetMethodImplementationFlags () {
  212. return MethodImplAttributes.IL | MethodImplAttributes.Managed | MethodImplAttributes.NoInlining;
  213. }
  214. public override ParameterInfo[] GetParameters ()
  215. {
  216. return GetParametersInternal ();
  217. }
  218. internal override ParameterInfo[] GetParametersInternal ()
  219. {
  220. if (parameters == null)
  221. return EmptyArray<ParameterInfo>.Value;
  222. ParameterInfo[] retval = new ParameterInfo [parameters.Length];
  223. for (int i = 0; i < parameters.Length; i++) {
  224. retval [i] = RuntimeParameterInfo.New (pinfo?[i + 1], parameters [i], this, i + 1);
  225. }
  226. return retval;
  227. }
  228. internal override int GetParametersCount ()
  229. {
  230. return parameters == null ? 0 : parameters.Length;
  231. }
  232. internal override Type GetParameterType (int pos) {
  233. return parameters [pos];
  234. }
  235. /*
  236. public override object Invoke (object obj, object[] parameters) {
  237. CreateDynMethod ();
  238. if (method == null)
  239. method = new RuntimeMethodInfo (mhandle);
  240. return method.Invoke (obj, parameters);
  241. }
  242. */
  243. public override object Invoke (object obj, BindingFlags invokeAttr,
  244. Binder binder, object[] parameters,
  245. CultureInfo culture)
  246. {
  247. try {
  248. CreateDynMethod ();
  249. if (method == null)
  250. method = new RuntimeMethodInfo (mhandle);
  251. return method.Invoke (obj, invokeAttr, binder, parameters, culture);
  252. }
  253. catch (MethodAccessException mae) {
  254. throw new TargetInvocationException ("Method cannot be invoked.", mae);
  255. }
  256. }
  257. public override bool IsDefined (Type attributeType, bool inherit) {
  258. if (attributeType == null)
  259. throw new ArgumentNullException ("attributeType");
  260. if (attributeType.IsAssignableFrom (typeof (MethodImplAttribute)))
  261. return true;
  262. else
  263. return false;
  264. }
  265. public override string ToString () {
  266. string parms = String.Empty;
  267. ParameterInfo[] p = GetParametersInternal ();
  268. for (int i = 0; i < p.Length; ++i) {
  269. if (i > 0)
  270. parms = parms + ", ";
  271. parms = parms + p [i].ParameterType.Name;
  272. }
  273. return ReturnType.Name+" "+Name+"("+parms+")";
  274. }
  275. public override MethodAttributes Attributes {
  276. get {
  277. return attributes;
  278. }
  279. }
  280. public override CallingConventions CallingConvention {
  281. get {
  282. return callingConvention;
  283. }
  284. }
  285. public override Type DeclaringType {
  286. get {
  287. return null;
  288. }
  289. }
  290. public bool InitLocals {
  291. get {
  292. return init_locals;
  293. }
  294. set {
  295. init_locals = value;
  296. }
  297. }
  298. public override RuntimeMethodHandle MethodHandle {
  299. get {
  300. return mhandle;
  301. }
  302. }
  303. public override Module Module {
  304. get {
  305. return module;
  306. }
  307. }
  308. public override string Name {
  309. get {
  310. return name;
  311. }
  312. }
  313. public override Type ReflectedType {
  314. get {
  315. return null;
  316. }
  317. }
  318. [MonoTODO("Not implemented")]
  319. public override ParameterInfo ReturnParameter {
  320. get {
  321. throw new NotImplementedException ();
  322. }
  323. }
  324. public override Type ReturnType {
  325. get {
  326. return returnType;
  327. }
  328. }
  329. [MonoTODO("Not implemented")]
  330. public override ICustomAttributeProvider ReturnTypeCustomAttributes {
  331. get {
  332. throw new NotImplementedException ();
  333. }
  334. }
  335. /*
  336. public override int MetadataToken {
  337. get {
  338. return 0;
  339. }
  340. }
  341. */
  342. private void RejectIfCreated () {
  343. if (mhandle.Value != IntPtr.Zero)
  344. throw new InvalidOperationException ("Type definition of the method is complete.");
  345. }
  346. internal int AddRef (object reference) {
  347. if (refs == null)
  348. refs = new object [4];
  349. if (nrefs >= refs.Length - 1) {
  350. object [] new_refs = new object [refs.Length * 2];
  351. System.Array.Copy (refs, new_refs, refs.Length);
  352. refs = new_refs;
  353. }
  354. refs [nrefs] = reference;
  355. /* Reserved by the runtime */
  356. refs [nrefs + 1] = null;
  357. nrefs += 2;
  358. return nrefs - 1;
  359. }
  360. // This class takes care of constructing the module in a thread safe manner
  361. static class AnonHostModuleHolder
  362. {
  363. public static readonly Module anon_host_module;
  364. static AnonHostModuleHolder () {
  365. AssemblyName aname = new AssemblyName ();
  366. aname.Name = "Anonymously Hosted DynamicMethods Assembly";
  367. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);
  368. anon_host_module = ab.GetManifestModule ();
  369. }
  370. public static Module AnonHostModule {
  371. get {
  372. return anon_host_module;
  373. }
  374. }
  375. }
  376. }
  377. internal class DynamicMethodTokenGenerator : TokenGenerator {
  378. private DynamicMethod m;
  379. public DynamicMethodTokenGenerator (DynamicMethod m) {
  380. this.m = m;
  381. }
  382. public int GetToken (string str) {
  383. return m.AddRef (str);
  384. }
  385. public int GetToken (MethodBase method, Type[] opt_param_types) {
  386. throw new InvalidOperationException ();
  387. }
  388. public int GetToken (MemberInfo member, bool create_open_instance) {
  389. return m.AddRef (member);
  390. }
  391. public int GetToken (SignatureHelper helper) {
  392. return m.AddRef (helper);
  393. }
  394. }
  395. }
  396. #endif