2009-07-28 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / DynamicMethod.cs
1 //
2 // System.Reflection.Emit.DynamicMethod.cs
3 //
4 // Author:
5 //   Paolo Molaro (lupus@ximian.com)
6 //   Zoltan Varga (vargaz@freemail.hu)
7 //
8 // (C) 2003 Ximian, Inc.  http://www.ximian.com
9 //
10
11 //
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 //
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:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
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.
32 //
33
34 #if NET_2_0 || BOOTSTRAP_NET_2_0
35
36 using System;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Globalization;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42
43 namespace System.Reflection.Emit {
44
45 #if NET_2_0
46         [ComVisible (true)]
47 #endif
48         public sealed class DynamicMethod : MethodInfo {
49
50 #pragma warning disable 169, 414
51                 #region Sync with reflection.h
52                 private RuntimeMethodHandle mhandle;
53                 private string name;
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;
62                 private int nrefs;
63                 private object[] refs;
64                 private IntPtr referenced_by;
65                 private Type owner;
66                 #endregion
67 #pragma warning restore 169, 414
68                 
69                 private Delegate deleg;
70                 private MonoMethod method;
71                 private ParameterBuilder[] pinfo;
72                 internal bool creating;
73
74                 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m) : this (name, returnType, parameterTypes, m, false) {
75                 }
76
77                 public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner) : this (name, returnType, parameterTypes, owner, false) {
78                 }
79
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) {
81                 }
82
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) {
84                 }
85
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) {
87                 }
88
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) {
90                 }
91
92                 public DynamicMethod (string name, Type returnType, Type[] parameterTypes) : this (name, returnType, parameterTypes, false) {
93                 }
94
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)
98                 {
99                 }
100
101                 DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type [] parameterTypes, Type owner, Module m, bool skipVisibility, bool anonHosted)
102                 {
103                         if (name == null)
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");
115                         }
116
117                         if (m == null)
118                                 m = AnonHostModuleHolder.anon_host_module;
119
120                         this.name = name;
121                         this.attributes = attributes | MethodAttributes.Static;
122                         this.callingConvention = callingConvention;
123                         this.returnType = returnType;
124                         this.parameters = parameterTypes;
125                         this.owner = owner;
126                         this.module = m;
127                         this.skipVisibility = skipVisibility;
128                 }
129
130                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
131                 private extern void create_dynamic_method (DynamicMethod m);
132
133                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
134                 private extern void destroy_dynamic_method (DynamicMethod m);
135
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.");
140
141                                 ilgen.label_fixup ();
142
143                                 // Have to create all DynamicMethods referenced by this one
144                                 try {
145                                         // Used to avoid cycles
146                                         creating = true;
147                                         if (refs != null) {
148                                                 for (int i = 0; i < refs.Length; ++i) {
149                                                         if (refs [i] is DynamicMethod) {
150                                                                 DynamicMethod m = (DynamicMethod)refs [i];
151                                                                 if (!m.creating)
152                                                                         m.CreateDynMethod ();
153                                                         }
154                                                 }
155                                         }
156                                 } finally {
157                                         creating = false;
158                                 }
159
160                                 create_dynamic_method (this);
161                         }
162                 }
163
164                 ~DynamicMethod ()
165                 {
166                         destroy_dynamic_method (this);
167                 }
168
169                 [ComVisible (true)]
170                 public Delegate CreateDelegate (Type delegateType)
171                 {
172                         if (delegateType == null)
173                                 throw new ArgumentNullException ("delegateType");
174                         if (deleg != null)
175                                 return deleg;
176
177                         CreateDynMethod ();
178
179                         deleg = Delegate.CreateDelegate (delegateType, this);
180                         return deleg;
181                 }
182
183                 [ComVisible (true)]
184                 public Delegate CreateDelegate (Type delegateType, object target)
185                 {
186                         if (delegateType == null)
187                                 throw new ArgumentNullException ("delegateType");
188
189                         CreateDynMethod ();
190
191                         /* Can't cache the delegate since it is different for each target */
192                         return Delegate.CreateDelegate (delegateType, target, this);
193                 }
194                 
195                 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName)
196                 {
197                         //
198                         // Extension: Mono allows position == 0 for the return attribute
199                         //
200                         if ((position < 0) || (position > parameters.Length))
201                                 throw new ArgumentOutOfRangeException ("position");
202
203                         RejectIfCreated ();
204
205                         ParameterBuilder pb = new ParameterBuilder (this, position, attributes, parameterName);
206                         if (pinfo == null)
207                                 pinfo = new ParameterBuilder [parameters.Length + 1];
208                         pinfo [position] = pb;
209                         return pb;
210                 }
211
212                 public override MethodInfo GetBaseDefinition () {
213                         return this;
214                 }
215
216                 [MonoTODO("Not implemented")]
217                 public override object[] GetCustomAttributes (bool inherit) {
218                         throw new NotImplementedException ();
219                 }
220
221                 [MonoTODO("Not implemented")]
222                 public override object[] GetCustomAttributes (Type attributeType,
223                                                                                                           bool inherit) {
224                         throw new NotImplementedException ();
225                 }
226
227                 [MonoTODO("Not implemented")]
228                 public DynamicILInfo GetDynamicILInfo () {
229                         throw new NotImplementedException ();
230                 }
231
232                 public ILGenerator GetILGenerator () {
233                         return GetILGenerator (64);
234                 }
235
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.");
242                         if (ilgen != null)
243                                 return ilgen;
244                         ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), streamSize);
245                         return ilgen;
246                 }               
247
248                 public override MethodImplAttributes GetMethodImplementationFlags () {
249                         return MethodImplAttributes.IL | MethodImplAttributes.Managed;
250                 }
251
252                 public override ParameterInfo[] GetParameters () {
253                         if (parameters == null)
254                                 return new ParameterInfo [0];
255
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);
259                         }
260                         return retval;
261                 }
262
263                 /*
264                 public override object Invoke (object obj, object[] parameters) {
265                         CreateDynMethod ();
266                         if (method == null)
267                                 method = new MonoMethod (mhandle);
268                         return method.Invoke (obj, parameters);
269                 }
270                 */
271
272                 public override object Invoke (object obj, BindingFlags invokeAttr,
273                                                                            Binder binder, object[] parameters,
274                                                                            CultureInfo culture)
275                 {
276                         try {
277                                 CreateDynMethod ();
278                                 if (method == null)
279                                         method = new MonoMethod (mhandle);
280
281                                 return method.Invoke (obj, parameters);
282                         }
283                         catch (MethodAccessException mae) {
284                                 throw new TargetInvocationException ("Method cannot be invoked.", mae);
285                         }
286                 }
287
288                 [MonoTODO("Not implemented")]
289                 public override bool IsDefined (Type attributeType, bool inherit) {
290                         throw new NotImplementedException ();
291                 }
292
293                 public override string ToString () {
294                         string parms = String.Empty;
295                         ParameterInfo[] p = GetParameters ();
296                         for (int i = 0; i < p.Length; ++i) {
297                                 if (i > 0)
298                                         parms = parms + ", ";
299                                 parms = parms + p [i].ParameterType.Name;
300                         }
301                         return ReturnType.Name+" "+Name+"("+parms+")";
302                 }
303
304                 public override MethodAttributes Attributes {
305                         get {
306                                 return attributes;
307                         }
308                 }
309
310                 public override CallingConventions CallingConvention {
311                         get {
312                                 return callingConvention;
313                         }
314                 }
315
316                 public override Type DeclaringType {
317                         get {
318                                 return null;
319                         }
320                 }
321
322                 public bool InitLocals {
323                         get {
324                                 return init_locals;
325                         }
326                         set {
327                                 init_locals = value;
328                         }
329                 }
330
331                 public override RuntimeMethodHandle MethodHandle {
332                         get {
333                                 return mhandle;
334                         }
335                 }
336
337                 public override Module Module {
338                         get {
339                                 return module;
340                         }
341                 }
342
343                 public override string Name {
344                         get {
345                                 return name;
346                         }
347                 }
348
349                 public override Type ReflectedType {
350                         get {
351                                 return null;
352                         }
353                 }
354
355                 [MonoTODO("Not implemented")]
356                 public override ParameterInfo ReturnParameter {
357                         get {
358                                 throw new NotImplementedException ();
359                         }
360                 }
361
362                 public override Type ReturnType {
363                         get {
364                                 return returnType;
365                         }
366                 }
367
368                 [MonoTODO("Not implemented")]
369                 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
370                         get {
371                                 throw new NotImplementedException ();
372                         }
373                 }
374
375 /*
376                 public override int MetadataToken {
377                         get {
378                                 return 0;
379                         }
380                 }
381 */
382
383                 private void RejectIfCreated () {
384                         if (mhandle.Value != IntPtr.Zero)
385                                 throw new InvalidOperationException ("Type definition of the method is complete.");
386                 }
387
388                 internal int AddRef (object reference) {
389                         if (refs == null)
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);
394                                 refs = new_refs;
395                         }
396                         refs [nrefs] = reference;
397                         /* Reserved by the runtime */
398                         refs [nrefs + 1] = null;
399                         nrefs += 2;
400                         return nrefs - 1;
401                 }
402
403                 // This class takes care of constructing the module in a thread safe manner
404                 class AnonHostModuleHolder {
405                         public static Module anon_host_module;
406
407                         static AnonHostModuleHolder () {
408                                 AssemblyName aname = new AssemblyName ();
409                                 aname.Name = "Anonymously Hosted DynamicMethods Assembly";
410                                 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);
411
412                                 anon_host_module = ab.GetManifestModule ();
413                         }
414                 }
415         }
416
417         internal class DynamicMethodTokenGenerator : TokenGenerator {
418
419                 private DynamicMethod m;
420
421                 public DynamicMethodTokenGenerator (DynamicMethod m) {
422                         this.m = m;
423                 }
424
425                 public int GetToken (string str) {
426                         return m.AddRef (str);
427                 }
428
429                 public int GetToken (MethodInfo method, Type[] opt_param_types) {
430                         throw new InvalidOperationException ();
431                 }
432
433                 public int GetToken (MemberInfo member) {
434                         return m.AddRef (member);
435                 }
436
437                 public int GetToken (SignatureHelper helper) {
438                         return m.AddRef (helper);
439                 }
440         }
441 }
442
443 #endif