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.
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Globalization;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
42 namespace System.Reflection.Emit {
45 [StructLayout (LayoutKind.Sequential)]
46 public sealed class DynamicMethod : MethodInfo {
48 #pragma warning disable 169, 414, 649
49 #region Sync with reflection.h
50 private RuntimeMethodHandle mhandle;
52 private Type returnType;
53 private Type[] parameters;
54 private MethodAttributes attributes;
55 private CallingConventions callingConvention;
56 private Module module;
57 private bool skipVisibility;
58 private bool init_locals = true;
59 private ILGenerator ilgen;
61 private object[] refs;
62 private IntPtr referenced_by;
65 #pragma warning restore 169, 414, 649
67 private Delegate deleg;
68 private MonoMethod method;
69 private ParameterBuilder[] pinfo;
70 internal bool creating;
71 private DynamicILInfo il_info;
73 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m) : this (name, returnType, parameterTypes, m, false) {
76 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner) : this (name, returnType, parameterTypes, owner, false) {
79 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, m, skipVisibility) {
82 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, skipVisibility) {
85 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) {
88 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) {
91 public DynamicMethod (string name, Type returnType, Type[] parameterTypes) : this (name, returnType, parameterTypes, false) {
94 [MonoTODO ("Visibility is not restricted")]
95 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility)
96 : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, null, restrictedSkipVisibility, true)
100 DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type [] parameterTypes, Type owner, Module m, bool skipVisibility, bool anonHosted)
103 throw new ArgumentNullException ("name");
104 if (returnType == null)
105 returnType = typeof (void);
106 if ((m == null) && !anonHosted)
107 throw new ArgumentNullException ("m");
108 if (returnType.IsByRef)
109 throw new ArgumentException ("Return type can't be a byref type", "returnType");
110 if (parameterTypes != null) {
111 for (int i = 0; i < parameterTypes.Length; ++i)
112 if (parameterTypes [i] == null)
113 throw new ArgumentException ("Parameter " + i + " is null", "parameterTypes");
115 if (owner != null && (owner.IsArray || owner.IsInterface)) {
116 throw new ArgumentException ("Owner can't be an array or an interface.");
120 m = AnonHostModuleHolder.AnonHostModule;
123 this.attributes = attributes | MethodAttributes.Static;
124 this.callingConvention = callingConvention;
125 this.returnType = returnType;
126 this.parameters = parameterTypes;
129 this.skipVisibility = skipVisibility;
132 [MethodImplAttribute(MethodImplOptions.InternalCall)]
133 private extern void create_dynamic_method (DynamicMethod m);
135 private void CreateDynMethod () {
136 if (mhandle.Value == IntPtr.Zero) {
137 if (ilgen == null || ilgen.ILOffset == 0)
138 throw new InvalidOperationException ("Method '" + name + "' does not have a method body.");
140 ilgen.label_fixup ();
142 // Have to create all DynamicMethods referenced by this one
144 // Used to avoid cycles
147 for (int i = 0; i < refs.Length; ++i) {
148 if (refs [i] is DynamicMethod) {
149 DynamicMethod m = (DynamicMethod)refs [i];
151 m.CreateDynMethod ();
159 create_dynamic_method (this);
164 public Delegate CreateDelegate (Type delegateType)
166 if (delegateType == null)
167 throw new ArgumentNullException ("delegateType");
173 deleg = Delegate.CreateDelegate (delegateType, this);
178 public Delegate CreateDelegate (Type delegateType, object target)
180 if (delegateType == null)
181 throw new ArgumentNullException ("delegateType");
185 /* Can't cache the delegate since it is different for each target */
186 return Delegate.CreateDelegate (delegateType, target, this);
189 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName)
192 // Extension: Mono allows position == 0 for the return attribute
194 if ((position < 0) || (position > parameters.Length))
195 throw new ArgumentOutOfRangeException ("position");
199 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, parameterName);
201 pinfo = new ParameterBuilder [parameters.Length + 1];
202 pinfo [position] = pb;
206 public override MethodInfo GetBaseDefinition () {
210 [MonoTODO("Not implemented")]
211 public override object[] GetCustomAttributes (bool inherit) {
212 throw new NotImplementedException ();
215 [MonoTODO("Not implemented")]
216 public override object[] GetCustomAttributes (Type attributeType,
218 throw new NotImplementedException ();
221 public DynamicILInfo GetDynamicILInfo () {
223 il_info = new DynamicILInfo (this);
227 public ILGenerator GetILGenerator () {
228 return GetILGenerator (64);
231 public ILGenerator GetILGenerator (int streamSize) {
232 if (((GetMethodImplementationFlags () & MethodImplAttributes.CodeTypeMask) !=
233 MethodImplAttributes.IL) ||
234 ((GetMethodImplementationFlags () & MethodImplAttributes.ManagedMask) !=
235 MethodImplAttributes.Managed))
236 throw new InvalidOperationException ("Method body should not exist.");
239 ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), streamSize);
243 public override MethodImplAttributes GetMethodImplementationFlags () {
244 return MethodImplAttributes.IL | MethodImplAttributes.Managed;
247 public override ParameterInfo[] GetParameters () {
248 if (parameters == null)
249 return new ParameterInfo [0];
251 ParameterInfo[] retval = new ParameterInfo [parameters.Length];
252 for (int i = 0; i < parameters.Length; i++) {
253 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
258 internal override int GetParameterCount ()
260 return parameters == null ? 0 : parameters.Length;
263 internal override Type GetParameterType (int pos) {
264 return parameters [pos];
268 public override object Invoke (object obj, object[] parameters) {
271 method = new MonoMethod (mhandle);
272 return method.Invoke (obj, parameters);
276 public override object Invoke (object obj, BindingFlags invokeAttr,
277 Binder binder, object[] parameters,
283 method = new MonoMethod (mhandle);
285 return method.Invoke (obj, parameters);
287 catch (MethodAccessException mae) {
288 throw new TargetInvocationException ("Method cannot be invoked.", mae);
292 [MonoTODO("Not implemented")]
293 public override bool IsDefined (Type attributeType, bool inherit) {
294 throw new NotImplementedException ();
297 public override string ToString () {
298 string parms = String.Empty;
299 ParameterInfo[] p = GetParameters ();
300 for (int i = 0; i < p.Length; ++i) {
302 parms = parms + ", ";
303 parms = parms + p [i].ParameterType.Name;
305 return ReturnType.Name+" "+Name+"("+parms+")";
308 public override MethodAttributes Attributes {
314 public override CallingConventions CallingConvention {
316 return callingConvention;
320 public override Type DeclaringType {
326 public bool InitLocals {
335 public override RuntimeMethodHandle MethodHandle {
341 public override Module Module {
347 public override string Name {
353 public override Type ReflectedType {
359 [MonoTODO("Not implemented")]
360 public override ParameterInfo ReturnParameter {
362 throw new NotImplementedException ();
366 public override Type ReturnType {
372 [MonoTODO("Not implemented")]
373 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
375 throw new NotImplementedException ();
380 public override int MetadataToken {
387 private void RejectIfCreated () {
388 if (mhandle.Value != IntPtr.Zero)
389 throw new InvalidOperationException ("Type definition of the method is complete.");
392 internal int AddRef (object reference) {
394 refs = new object [4];
395 if (nrefs >= refs.Length - 1) {
396 object [] new_refs = new object [refs.Length * 2];
397 System.Array.Copy (refs, new_refs, refs.Length);
400 refs [nrefs] = reference;
401 /* Reserved by the runtime */
402 refs [nrefs + 1] = null;
407 // This class takes care of constructing the module in a thread safe manner
408 class AnonHostModuleHolder {
409 public static Module anon_host_module;
411 static AnonHostModuleHolder () {
412 AssemblyName aname = new AssemblyName ();
413 aname.Name = "Anonymously Hosted DynamicMethods Assembly";
414 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);
416 anon_host_module = ab.GetManifestModule ();
419 public static Module AnonHostModule {
421 return anon_host_module;
427 internal class DynamicMethodTokenGenerator : TokenGenerator {
429 private DynamicMethod m;
431 public DynamicMethodTokenGenerator (DynamicMethod m) {
435 public int GetToken (string str) {
436 return m.AddRef (str);
439 public int GetToken (MethodInfo method, Type[] opt_param_types) {
440 throw new InvalidOperationException ();
443 public int GetToken (MemberInfo member, bool create_open_instance) {
444 return m.AddRef (member);
447 public int GetToken (SignatureHelper helper) {
448 return m.AddRef (helper);