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");
117 m = AnonHostModuleHolder.AnonHostModule;
120 this.attributes = attributes | MethodAttributes.Static;
121 this.callingConvention = callingConvention;
122 this.returnType = returnType;
123 this.parameters = parameterTypes;
126 this.skipVisibility = skipVisibility;
129 [MethodImplAttribute(MethodImplOptions.InternalCall)]
130 private extern void create_dynamic_method (DynamicMethod m);
132 private void CreateDynMethod () {
133 if (mhandle.Value == IntPtr.Zero) {
134 if (ilgen == null || ilgen.ILOffset == 0)
135 throw new InvalidOperationException ("Method '" + name + "' does not have a method body.");
137 ilgen.label_fixup ();
139 // Have to create all DynamicMethods referenced by this one
141 // Used to avoid cycles
144 for (int i = 0; i < refs.Length; ++i) {
145 if (refs [i] is DynamicMethod) {
146 DynamicMethod m = (DynamicMethod)refs [i];
148 m.CreateDynMethod ();
156 create_dynamic_method (this);
161 public Delegate CreateDelegate (Type delegateType)
163 if (delegateType == null)
164 throw new ArgumentNullException ("delegateType");
170 deleg = Delegate.CreateDelegate (delegateType, this);
175 public Delegate CreateDelegate (Type delegateType, object target)
177 if (delegateType == null)
178 throw new ArgumentNullException ("delegateType");
182 /* Can't cache the delegate since it is different for each target */
183 return Delegate.CreateDelegate (delegateType, target, this);
186 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName)
189 // Extension: Mono allows position == 0 for the return attribute
191 if ((position < 0) || (position > parameters.Length))
192 throw new ArgumentOutOfRangeException ("position");
196 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, parameterName);
198 pinfo = new ParameterBuilder [parameters.Length + 1];
199 pinfo [position] = pb;
203 public override MethodInfo GetBaseDefinition () {
207 [MonoTODO("Not implemented")]
208 public override object[] GetCustomAttributes (bool inherit) {
209 throw new NotImplementedException ();
212 [MonoTODO("Not implemented")]
213 public override object[] GetCustomAttributes (Type attributeType,
215 throw new NotImplementedException ();
218 public DynamicILInfo GetDynamicILInfo () {
220 il_info = new DynamicILInfo (this);
224 public ILGenerator GetILGenerator () {
225 return GetILGenerator (64);
228 public ILGenerator GetILGenerator (int streamSize) {
229 if (((GetMethodImplementationFlags () & MethodImplAttributes.CodeTypeMask) !=
230 MethodImplAttributes.IL) ||
231 ((GetMethodImplementationFlags () & MethodImplAttributes.ManagedMask) !=
232 MethodImplAttributes.Managed))
233 throw new InvalidOperationException ("Method body should not exist.");
236 ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), streamSize);
240 public override MethodImplAttributes GetMethodImplementationFlags () {
241 return MethodImplAttributes.IL | MethodImplAttributes.Managed;
244 public override ParameterInfo[] GetParameters () {
245 if (parameters == null)
246 return new ParameterInfo [0];
248 ParameterInfo[] retval = new ParameterInfo [parameters.Length];
249 for (int i = 0; i < parameters.Length; i++) {
250 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
255 internal override int GetParameterCount ()
257 return parameters == null ? 0 : parameters.Length;
260 internal override Type GetParameterType (int pos) {
261 return parameters [pos];
265 public override object Invoke (object obj, object[] parameters) {
268 method = new MonoMethod (mhandle);
269 return method.Invoke (obj, parameters);
273 public override object Invoke (object obj, BindingFlags invokeAttr,
274 Binder binder, object[] parameters,
280 method = new MonoMethod (mhandle);
282 return method.Invoke (obj, parameters);
284 catch (MethodAccessException mae) {
285 throw new TargetInvocationException ("Method cannot be invoked.", mae);
289 [MonoTODO("Not implemented")]
290 public override bool IsDefined (Type attributeType, bool inherit) {
291 throw new NotImplementedException ();
294 public override string ToString () {
295 string parms = String.Empty;
296 ParameterInfo[] p = GetParameters ();
297 for (int i = 0; i < p.Length; ++i) {
299 parms = parms + ", ";
300 parms = parms + p [i].ParameterType.Name;
302 return ReturnType.Name+" "+Name+"("+parms+")";
305 public override MethodAttributes Attributes {
311 public override CallingConventions CallingConvention {
313 return callingConvention;
317 public override Type DeclaringType {
323 public bool InitLocals {
332 public override RuntimeMethodHandle MethodHandle {
338 public override Module Module {
344 public override string Name {
350 public override Type ReflectedType {
356 [MonoTODO("Not implemented")]
357 public override ParameterInfo ReturnParameter {
359 throw new NotImplementedException ();
363 public override Type ReturnType {
369 [MonoTODO("Not implemented")]
370 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
372 throw new NotImplementedException ();
377 public override int MetadataToken {
384 private void RejectIfCreated () {
385 if (mhandle.Value != IntPtr.Zero)
386 throw new InvalidOperationException ("Type definition of the method is complete.");
389 internal int AddRef (object reference) {
391 refs = new object [4];
392 if (nrefs >= refs.Length - 1) {
393 object [] new_refs = new object [refs.Length * 2];
394 System.Array.Copy (refs, new_refs, refs.Length);
397 refs [nrefs] = reference;
398 /* Reserved by the runtime */
399 refs [nrefs + 1] = null;
404 // This class takes care of constructing the module in a thread safe manner
405 class AnonHostModuleHolder {
406 public static Module anon_host_module;
408 static AnonHostModuleHolder () {
409 AssemblyName aname = new AssemblyName ();
410 aname.Name = "Anonymously Hosted DynamicMethods Assembly";
411 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);
413 anon_host_module = ab.GetManifestModule ();
416 public static Module AnonHostModule {
418 return anon_host_module;
424 internal class DynamicMethodTokenGenerator : TokenGenerator {
426 private DynamicMethod m;
428 public DynamicMethodTokenGenerator (DynamicMethod m) {
432 public int GetToken (string str) {
433 return m.AddRef (str);
436 public int GetToken (MethodInfo method, Type[] opt_param_types) {
437 throw new InvalidOperationException ();
440 public int GetToken (MemberInfo member, bool create_open_instance) {
441 return m.AddRef (member);
444 public int GetToken (SignatureHelper helper) {
445 return m.AddRef (helper);