DynamicMethod.cs 13 KB

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