DynamicMethod.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 NET_2_0 || BOOTSTRAP_NET_2_0
  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. #if NET_2_0
  41. [ComVisible (true)]
  42. #endif
  43. public sealed class DynamicMethod : MethodInfo {
  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. private Delegate deleg;
  61. private MonoMethod method;
  62. private ParameterBuilder[] pinfo;
  63. internal bool creating;
  64. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m) : this (name, returnType, parameterTypes, m, false) {
  65. }
  66. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner) : this (name, returnType, parameterTypes, owner, false) {
  67. }
  68. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, m, skipVisibility) {
  69. }
  70. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, skipVisibility) {
  71. }
  72. 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) {
  73. }
  74. 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) {
  75. }
  76. public DynamicMethod (string name, Type returnType, Type[] parameterTypes) : this (name, returnType, parameterTypes, false) {
  77. }
  78. public DynamicMethod (string name, Type returnType, Type[] parameterTypes, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, null, false, true) {
  79. }
  80. DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type [] parameterTypes, Type owner, Module m, bool skipVisibility, bool anonHosted)
  81. {
  82. if (name == null)
  83. throw new ArgumentNullException ("name");
  84. if (returnType == null)
  85. returnType = typeof (void);
  86. if ((m == null) && !anonHosted)
  87. throw new ArgumentNullException ("m");
  88. if (returnType.IsByRef)
  89. throw new ArgumentException ("Return type can't be a byref type", "returnType");
  90. if (parameterTypes != null) {
  91. for (int i = 0; i < parameterTypes.Length; ++i)
  92. if (parameterTypes [i] == null)
  93. throw new ArgumentException ("Parameter " + i + " is null", "parameterTypes");
  94. }
  95. if (m == null)
  96. m = AnonHostModuleHolder.anon_host_module;
  97. this.name = name;
  98. this.attributes = attributes | MethodAttributes.Static;
  99. this.callingConvention = callingConvention;
  100. this.returnType = returnType;
  101. this.parameters = parameterTypes;
  102. this.owner = owner;
  103. this.module = m;
  104. this.skipVisibility = skipVisibility;
  105. }
  106. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  107. private extern void create_dynamic_method (DynamicMethod m);
  108. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  109. private extern void destroy_dynamic_method (DynamicMethod m);
  110. private void CreateDynMethod () {
  111. if (mhandle.Value == IntPtr.Zero) {
  112. if (ilgen == null || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0))
  113. throw new InvalidOperationException ("Method '" + name + "' does not have a method body.");
  114. ilgen.label_fixup ();
  115. // Have to create all DynamicMethods referenced by this one
  116. try {
  117. // Used to avoid cycles
  118. creating = true;
  119. if (refs != null) {
  120. for (int i = 0; i < refs.Length; ++i) {
  121. if (refs [i] is DynamicMethod) {
  122. DynamicMethod m = (DynamicMethod)refs [i];
  123. if (!m.creating)
  124. m.CreateDynMethod ();
  125. }
  126. }
  127. }
  128. } finally {
  129. creating = false;
  130. }
  131. create_dynamic_method (this);
  132. }
  133. }
  134. ~DynamicMethod ()
  135. {
  136. destroy_dynamic_method (this);
  137. }
  138. [ComVisible (true)]
  139. public Delegate CreateDelegate (Type delegateType)
  140. {
  141. if (delegateType == null)
  142. throw new ArgumentNullException ("delegateType");
  143. if (deleg != null)
  144. return deleg;
  145. CreateDynMethod ();
  146. deleg = Delegate.CreateDelegate (delegateType, this);
  147. return deleg;
  148. }
  149. [ComVisible (true)]
  150. public Delegate CreateDelegate (Type delegateType, object target)
  151. {
  152. if (delegateType == null)
  153. throw new ArgumentNullException ("delegateType");
  154. CreateDynMethod ();
  155. /* Can't cache the delegate since it is different for each target */
  156. return Delegate.CreateDelegate (delegateType, target, this);
  157. }
  158. public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
  159. {
  160. //
  161. // Extension: Mono allows position == 0 for the return attribute
  162. //
  163. if ((position < 0) || (position > parameters.Length))
  164. throw new ArgumentOutOfRangeException ("position");
  165. RejectIfCreated ();
  166. ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
  167. if (pinfo == null)
  168. pinfo = new ParameterBuilder [parameters.Length + 1];
  169. pinfo [position] = pb;
  170. return pb;
  171. }
  172. public override MethodInfo GetBaseDefinition () {
  173. return this;
  174. }
  175. [MonoTODO("Not implemented")]
  176. public override object[] GetCustomAttributes (bool inherit) {
  177. throw new NotImplementedException ();
  178. }
  179. [MonoTODO("Not implemented")]
  180. public override object[] GetCustomAttributes (Type attributeType,
  181. bool inherit) {
  182. throw new NotImplementedException ();
  183. }
  184. [MonoTODO("Not implemented")]
  185. public DynamicILInfo GetDynamicILInfo () {
  186. throw new NotImplementedException ();
  187. }
  188. public ILGenerator GetILGenerator () {
  189. return GetILGenerator (64);
  190. }
  191. public ILGenerator GetILGenerator (int size) {
  192. if (((GetMethodImplementationFlags () & MethodImplAttributes.CodeTypeMask) !=
  193. MethodImplAttributes.IL) ||
  194. ((GetMethodImplementationFlags () & MethodImplAttributes.ManagedMask) !=
  195. MethodImplAttributes.Managed))
  196. throw new InvalidOperationException ("Method body should not exist.");
  197. if (ilgen != null)
  198. return ilgen;
  199. ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), size);
  200. return ilgen;
  201. }
  202. public override MethodImplAttributes GetMethodImplementationFlags () {
  203. return MethodImplAttributes.IL | MethodImplAttributes.Managed;
  204. }
  205. public override ParameterInfo[] GetParameters () {
  206. if (parameters == null)
  207. return new ParameterInfo [0];
  208. ParameterInfo[] retval = new ParameterInfo [parameters.Length];
  209. for (int i = 0; i < parameters.Length; i++) {
  210. retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
  211. }
  212. return retval;
  213. }
  214. /*
  215. public override object Invoke (object obj, object[] parameters) {
  216. CreateDynMethod ();
  217. if (method == null)
  218. method = new MonoMethod (mhandle);
  219. return method.Invoke (obj, parameters);
  220. }
  221. */
  222. public override object Invoke (object obj, BindingFlags invokeAttr,
  223. Binder binder, object[] parameters,
  224. CultureInfo culture) {
  225. CreateDynMethod ();
  226. if (method == null)
  227. method = new MonoMethod (mhandle);
  228. return method.Invoke (obj, parameters);
  229. }
  230. [MonoTODO("Not implemented")]
  231. public override bool IsDefined (Type attributeType, bool inherit) {
  232. throw new NotImplementedException ();
  233. }
  234. public override string ToString () {
  235. string parms = String.Empty;
  236. ParameterInfo[] p = GetParameters ();
  237. for (int i = 0; i < p.Length; ++i) {
  238. if (i > 0)
  239. parms = parms + ", ";
  240. parms = parms + p [i].ParameterType.Name;
  241. }
  242. return ReturnType.Name+" "+Name+"("+parms+")";
  243. }
  244. public override MethodAttributes Attributes {
  245. get {
  246. return attributes;
  247. }
  248. }
  249. public override CallingConventions CallingConvention {
  250. get {
  251. return callingConvention;
  252. }
  253. }
  254. public override Type DeclaringType {
  255. get {
  256. return null;
  257. }
  258. }
  259. public bool InitLocals {
  260. get {
  261. return init_locals;
  262. }
  263. set {
  264. init_locals = value;
  265. }
  266. }
  267. public override RuntimeMethodHandle MethodHandle {
  268. get {
  269. return mhandle;
  270. }
  271. }
  272. public override Module Module {
  273. get {
  274. return module;
  275. }
  276. }
  277. public override string Name {
  278. get {
  279. return name;
  280. }
  281. }
  282. public override Type ReflectedType {
  283. get {
  284. return null;
  285. }
  286. }
  287. [MonoTODO("Not implemented")]
  288. public override ParameterInfo ReturnParameter {
  289. get {
  290. throw new NotImplementedException ();
  291. }
  292. }
  293. public override Type ReturnType {
  294. get {
  295. return returnType;
  296. }
  297. }
  298. [MonoTODO("Not implemented")]
  299. public override ICustomAttributeProvider ReturnTypeCustomAttributes {
  300. get {
  301. throw new NotImplementedException ();
  302. }
  303. }
  304. /*
  305. public override int MetadataToken {
  306. get {
  307. return 0;
  308. }
  309. }
  310. */
  311. private void RejectIfCreated () {
  312. if (mhandle.Value != IntPtr.Zero)
  313. throw new InvalidOperationException ("Type definition of the method is complete.");
  314. }
  315. private Exception NotSupported () {
  316. return new NotSupportedException ("The invoked member is not supported on a dynamic method.");
  317. }
  318. internal int AddRef (object reference) {
  319. if (refs == null)
  320. refs = new object [4];
  321. if (nrefs >= refs.Length - 1) {
  322. object [] new_refs = new object [refs.Length * 2];
  323. System.Array.Copy (refs, new_refs, refs.Length);
  324. refs = new_refs;
  325. }
  326. refs [nrefs] = reference;
  327. /* Reserved by the runtime */
  328. refs [nrefs + 1] = null;
  329. nrefs += 2;
  330. return nrefs - 1;
  331. }
  332. // This class takes care of constructing the module in a thread safe manner
  333. class AnonHostModuleHolder {
  334. public static Module anon_host_module;
  335. static AnonHostModuleHolder () {
  336. AssemblyName aname = new AssemblyName ();
  337. aname.Name = "Anonymously Hosted DynamicMethods Assembly";
  338. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);
  339. anon_host_module = ab.GetManifestModule ();
  340. }
  341. }
  342. }
  343. internal class DynamicMethodTokenGenerator : TokenGenerator {
  344. private DynamicMethod m;
  345. public DynamicMethodTokenGenerator (DynamicMethod m) {
  346. this.m = m;
  347. }
  348. public int GetToken (string str) {
  349. return m.AddRef (str);
  350. }
  351. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  352. throw new InvalidOperationException ();
  353. }
  354. public int GetToken (MemberInfo member) {
  355. return m.AddRef (member);
  356. }
  357. public int GetToken (SignatureHelper helper) {
  358. return m.AddRef (helper);
  359. }
  360. }
  361. }
  362. #endif