DynamicMethod.cs 13 KB

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