DynamicMethod.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. private void CreateDynMethod () {
  111. if (mhandle.Value == IntPtr.Zero) {
  112. if (ilgen == null || ilgen.ILOffset == 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. [ComVisible (true)]
  135. public Delegate CreateDelegate (Type delegateType)
  136. {
  137. if (delegateType == null)
  138. throw new ArgumentNullException ("delegateType");
  139. if (deleg != null)
  140. return deleg;
  141. CreateDynMethod ();
  142. deleg = Delegate.CreateDelegate (delegateType, this);
  143. return deleg;
  144. }
  145. [ComVisible (true)]
  146. public Delegate CreateDelegate (Type delegateType, object target)
  147. {
  148. if (delegateType == null)
  149. throw new ArgumentNullException ("delegateType");
  150. CreateDynMethod ();
  151. /* Can't cache the delegate since it is different for each target */
  152. return Delegate.CreateDelegate (delegateType, target, this);
  153. }
  154. public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName)
  155. {
  156. //
  157. // Extension: Mono allows position == 0 for the return attribute
  158. //
  159. if ((position < 0) || (position > parameters.Length))
  160. throw new ArgumentOutOfRangeException ("position");
  161. RejectIfCreated ();
  162. ParameterBuilder pb = new ParameterBuilder (this, position, attributes, parameterName);
  163. if (pinfo == null)
  164. pinfo = new ParameterBuilder [parameters.Length + 1];
  165. pinfo [position] = pb;
  166. return pb;
  167. }
  168. public override MethodInfo GetBaseDefinition () {
  169. return this;
  170. }
  171. [MonoTODO("Not implemented")]
  172. public override object[] GetCustomAttributes (bool inherit) {
  173. throw new NotImplementedException ();
  174. }
  175. [MonoTODO("Not implemented")]
  176. public override object[] GetCustomAttributes (Type attributeType,
  177. bool inherit) {
  178. throw new NotImplementedException ();
  179. }
  180. [MonoTODO("Not implemented")]
  181. public DynamicILInfo GetDynamicILInfo () {
  182. throw new NotImplementedException ();
  183. }
  184. public ILGenerator GetILGenerator () {
  185. return GetILGenerator (64);
  186. }
  187. public ILGenerator GetILGenerator (int streamSize) {
  188. if (((GetMethodImplementationFlags () & MethodImplAttributes.CodeTypeMask) !=
  189. MethodImplAttributes.IL) ||
  190. ((GetMethodImplementationFlags () & MethodImplAttributes.ManagedMask) !=
  191. MethodImplAttributes.Managed))
  192. throw new InvalidOperationException ("Method body should not exist.");
  193. if (ilgen != null)
  194. return ilgen;
  195. ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), streamSize);
  196. return ilgen;
  197. }
  198. public override MethodImplAttributes GetMethodImplementationFlags () {
  199. return MethodImplAttributes.IL | MethodImplAttributes.Managed;
  200. }
  201. public override ParameterInfo[] GetParameters () {
  202. if (parameters == null)
  203. return new ParameterInfo [0];
  204. ParameterInfo[] retval = new ParameterInfo [parameters.Length];
  205. for (int i = 0; i < parameters.Length; i++) {
  206. retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
  207. }
  208. return retval;
  209. }
  210. internal override int GetParameterCount ()
  211. {
  212. return parameters == null ? 0 : parameters.Length;
  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. {
  226. try {
  227. CreateDynMethod ();
  228. if (method == null)
  229. method = new MonoMethod (mhandle);
  230. return method.Invoke (obj, parameters);
  231. }
  232. catch (MethodAccessException mae) {
  233. throw new TargetInvocationException ("Method cannot be invoked.", mae);
  234. }
  235. }
  236. [MonoTODO("Not implemented")]
  237. public override bool IsDefined (Type attributeType, bool inherit) {
  238. throw new NotImplementedException ();
  239. }
  240. public override string ToString () {
  241. string parms = String.Empty;
  242. ParameterInfo[] p = GetParameters ();
  243. for (int i = 0; i < p.Length; ++i) {
  244. if (i > 0)
  245. parms = parms + ", ";
  246. parms = parms + p [i].ParameterType.Name;
  247. }
  248. return ReturnType.Name+" "+Name+"("+parms+")";
  249. }
  250. public override MethodAttributes Attributes {
  251. get {
  252. return attributes;
  253. }
  254. }
  255. public override CallingConventions CallingConvention {
  256. get {
  257. return callingConvention;
  258. }
  259. }
  260. public override Type DeclaringType {
  261. get {
  262. return null;
  263. }
  264. }
  265. public bool InitLocals {
  266. get {
  267. return init_locals;
  268. }
  269. set {
  270. init_locals = value;
  271. }
  272. }
  273. public override RuntimeMethodHandle MethodHandle {
  274. get {
  275. return mhandle;
  276. }
  277. }
  278. public override Module Module {
  279. get {
  280. return module;
  281. }
  282. }
  283. public override string Name {
  284. get {
  285. return name;
  286. }
  287. }
  288. public override Type ReflectedType {
  289. get {
  290. return null;
  291. }
  292. }
  293. [MonoTODO("Not implemented")]
  294. public override ParameterInfo ReturnParameter {
  295. get {
  296. throw new NotImplementedException ();
  297. }
  298. }
  299. public override Type ReturnType {
  300. get {
  301. return returnType;
  302. }
  303. }
  304. [MonoTODO("Not implemented")]
  305. public override ICustomAttributeProvider ReturnTypeCustomAttributes {
  306. get {
  307. throw new NotImplementedException ();
  308. }
  309. }
  310. /*
  311. public override int MetadataToken {
  312. get {
  313. return 0;
  314. }
  315. }
  316. */
  317. private void RejectIfCreated () {
  318. if (mhandle.Value != IntPtr.Zero)
  319. throw new InvalidOperationException ("Type definition of the method is complete.");
  320. }
  321. internal int AddRef (object reference) {
  322. if (refs == null)
  323. refs = new object [4];
  324. if (nrefs >= refs.Length - 1) {
  325. object [] new_refs = new object [refs.Length * 2];
  326. System.Array.Copy (refs, new_refs, refs.Length);
  327. refs = new_refs;
  328. }
  329. refs [nrefs] = reference;
  330. /* Reserved by the runtime */
  331. refs [nrefs + 1] = null;
  332. nrefs += 2;
  333. return nrefs - 1;
  334. }
  335. // This class takes care of constructing the module in a thread safe manner
  336. class AnonHostModuleHolder {
  337. public static Module anon_host_module;
  338. static AnonHostModuleHolder () {
  339. AssemblyName aname = new AssemblyName ();
  340. aname.Name = "Anonymously Hosted DynamicMethods Assembly";
  341. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);
  342. anon_host_module = ab.GetManifestModule ();
  343. }
  344. }
  345. }
  346. internal class DynamicMethodTokenGenerator : TokenGenerator {
  347. private DynamicMethod m;
  348. public DynamicMethodTokenGenerator (DynamicMethod m) {
  349. this.m = m;
  350. }
  351. public int GetToken (string str) {
  352. return m.AddRef (str);
  353. }
  354. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  355. throw new InvalidOperationException ();
  356. }
  357. public int GetToken (MemberInfo member, bool create_open_instance) {
  358. return m.AddRef (member);
  359. }
  360. public int GetToken (SignatureHelper helper) {
  361. return m.AddRef (helper);
  362. }
  363. }
  364. }