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