2 // System.Reflection.Emit.DynamicMethod.cs
5 // Paolo Molaro (lupus@ximian.com)
6 // Zoltan Varga (vargaz@freemail.hu)
8 // (C) 2003 Ximian, Inc. http://www.ximian.com
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 #if NET_2_0 || BOOTSTRAP_NET_2_0
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Globalization;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
43 namespace System.Reflection.Emit {
48 public sealed class DynamicMethod : MethodInfo {
50 #pragma warning disable 169, 414
51 #region Sync with reflection.h
52 private RuntimeMethodHandle mhandle;
54 private Type returnType;
55 private Type[] parameters;
56 private MethodAttributes attributes;
57 private CallingConventions callingConvention;
58 private Module module;
59 private bool skipVisibility;
60 private bool init_locals = true;
61 private ILGenerator ilgen;
63 private object[] refs;
64 private IntPtr referenced_by;
67 #pragma warning restore 169, 414
69 private Delegate deleg;
70 private MonoMethod method;
71 private ParameterBuilder[] pinfo;
72 internal bool creating;
74 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m) : this (name, returnType, parameterTypes, m, false) {
77 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner) : this (name, returnType, parameterTypes, owner, false) {
80 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, m, skipVisibility) {
83 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, skipVisibility) {
86 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) {
89 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) {
92 public DynamicMethod (string name, Type returnType, Type[] parameterTypes) : this (name, returnType, parameterTypes, false) {
95 [MonoTODO ("Visibility is not restricted")]
96 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility)
97 : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, null, restrictedSkipVisibility, true)
101 DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type [] parameterTypes, Type owner, Module m, bool skipVisibility, bool anonHosted)
104 throw new ArgumentNullException ("name");
105 if (returnType == null)
106 returnType = typeof (void);
107 if ((m == null) && !anonHosted)
108 throw new ArgumentNullException ("m");
109 if (returnType.IsByRef)
110 throw new ArgumentException ("Return type can't be a byref type", "returnType");
111 if (parameterTypes != null) {
112 for (int i = 0; i < parameterTypes.Length; ++i)
113 if (parameterTypes [i] == null)
114 throw new ArgumentException ("Parameter " + i + " is null", "parameterTypes");
118 m = AnonHostModuleHolder.anon_host_module;
121 this.attributes = attributes | MethodAttributes.Static;
122 this.callingConvention = callingConvention;
123 this.returnType = returnType;
124 this.parameters = parameterTypes;
127 this.skipVisibility = skipVisibility;
130 [MethodImplAttribute(MethodImplOptions.InternalCall)]
131 private extern void create_dynamic_method (DynamicMethod m);
133 [MethodImplAttribute(MethodImplOptions.InternalCall)]
134 private extern void destroy_dynamic_method (DynamicMethod m);
136 private void CreateDynMethod () {
137 if (mhandle.Value == IntPtr.Zero) {
138 if (ilgen == null || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0))
139 throw new InvalidOperationException ("Method '" + name + "' does not have a method body.");
141 ilgen.label_fixup ();
143 // Have to create all DynamicMethods referenced by this one
145 // Used to avoid cycles
148 for (int i = 0; i < refs.Length; ++i) {
149 if (refs [i] is DynamicMethod) {
150 DynamicMethod m = (DynamicMethod)refs [i];
152 m.CreateDynMethod ();
160 create_dynamic_method (this);
166 destroy_dynamic_method (this);
170 public Delegate CreateDelegate (Type delegateType)
172 if (delegateType == null)
173 throw new ArgumentNullException ("delegateType");
179 deleg = Delegate.CreateDelegate (delegateType, this);
184 public Delegate CreateDelegate (Type delegateType, object target)
186 if (delegateType == null)
187 throw new ArgumentNullException ("delegateType");
191 /* Can't cache the delegate since it is different for each target */
192 return Delegate.CreateDelegate (delegateType, target, this);
195 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName)
198 // Extension: Mono allows position == 0 for the return attribute
200 if ((position < 0) || (position > parameters.Length))
201 throw new ArgumentOutOfRangeException ("position");
205 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, parameterName);
207 pinfo = new ParameterBuilder [parameters.Length + 1];
208 pinfo [position] = pb;
212 public override MethodInfo GetBaseDefinition () {
216 [MonoTODO("Not implemented")]
217 public override object[] GetCustomAttributes (bool inherit) {
218 throw new NotImplementedException ();
221 [MonoTODO("Not implemented")]
222 public override object[] GetCustomAttributes (Type attributeType,
224 throw new NotImplementedException ();
227 [MonoTODO("Not implemented")]
228 public DynamicILInfo GetDynamicILInfo () {
229 throw new NotImplementedException ();
232 public ILGenerator GetILGenerator () {
233 return GetILGenerator (64);
236 public ILGenerator GetILGenerator (int streamSize) {
237 if (((GetMethodImplementationFlags () & MethodImplAttributes.CodeTypeMask) !=
238 MethodImplAttributes.IL) ||
239 ((GetMethodImplementationFlags () & MethodImplAttributes.ManagedMask) !=
240 MethodImplAttributes.Managed))
241 throw new InvalidOperationException ("Method body should not exist.");
244 ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), streamSize);
248 public override MethodImplAttributes GetMethodImplementationFlags () {
249 return MethodImplAttributes.IL | MethodImplAttributes.Managed;
252 public override ParameterInfo[] GetParameters () {
253 if (parameters == null)
254 return new ParameterInfo [0];
256 ParameterInfo[] retval = new ParameterInfo [parameters.Length];
257 for (int i = 0; i < parameters.Length; i++) {
258 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
264 public override object Invoke (object obj, object[] parameters) {
267 method = new MonoMethod (mhandle);
268 return method.Invoke (obj, parameters);
272 public override object Invoke (object obj, BindingFlags invokeAttr,
273 Binder binder, object[] parameters,
279 method = new MonoMethod (mhandle);
281 return method.Invoke (obj, parameters);
283 catch (MethodAccessException mae) {
284 throw new TargetInvocationException ("Method cannot be invoked.", mae);
288 [MonoTODO("Not implemented")]
289 public override bool IsDefined (Type attributeType, bool inherit) {
290 throw new NotImplementedException ();
293 public override string ToString () {
294 string parms = String.Empty;
295 ParameterInfo[] p = GetParameters ();
296 for (int i = 0; i < p.Length; ++i) {
298 parms = parms + ", ";
299 parms = parms + p [i].ParameterType.Name;
301 return ReturnType.Name+" "+Name+"("+parms+")";
304 public override MethodAttributes Attributes {
310 public override CallingConventions CallingConvention {
312 return callingConvention;
316 public override Type DeclaringType {
322 public bool InitLocals {
331 public override RuntimeMethodHandle MethodHandle {
337 public override Module Module {
343 public override string Name {
349 public override Type ReflectedType {
355 [MonoTODO("Not implemented")]
356 public override ParameterInfo ReturnParameter {
358 throw new NotImplementedException ();
362 public override Type ReturnType {
368 [MonoTODO("Not implemented")]
369 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
371 throw new NotImplementedException ();
376 public override int MetadataToken {
383 private void RejectIfCreated () {
384 if (mhandle.Value != IntPtr.Zero)
385 throw new InvalidOperationException ("Type definition of the method is complete.");
388 internal int AddRef (object reference) {
390 refs = new object [4];
391 if (nrefs >= refs.Length - 1) {
392 object [] new_refs = new object [refs.Length * 2];
393 System.Array.Copy (refs, new_refs, refs.Length);
396 refs [nrefs] = reference;
397 /* Reserved by the runtime */
398 refs [nrefs + 1] = null;
403 // This class takes care of constructing the module in a thread safe manner
404 class AnonHostModuleHolder {
405 public static Module anon_host_module;
407 static AnonHostModuleHolder () {
408 AssemblyName aname = new AssemblyName ();
409 aname.Name = "Anonymously Hosted DynamicMethods Assembly";
410 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);
412 anon_host_module = ab.GetManifestModule ();
417 internal class DynamicMethodTokenGenerator : TokenGenerator {
419 private DynamicMethod m;
421 public DynamicMethodTokenGenerator (DynamicMethod m) {
425 public int GetToken (string str) {
426 return m.AddRef (str);
429 public int GetToken (MethodInfo method, Type[] opt_param_types) {
430 throw new InvalidOperationException ();
433 public int GetToken (MemberInfo member) {
434 return m.AddRef (member);
437 public int GetToken (SignatureHelper helper) {
438 return m.AddRef (helper);