Merge pull request #498 from Unroll-Me/master
[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 !FULL_AOT_RUNTIME
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         [ComVisible (true)]
46         [StructLayout (LayoutKind.Sequential)]
47         public sealed class DynamicMethod : MethodInfo {
48
49 #pragma warning disable 169, 414, 649
50                 #region Sync with reflection.h
51                 private RuntimeMethodHandle mhandle;
52                 private string name;
53                 private Type returnType;
54                 private Type[] parameters;
55                 private MethodAttributes attributes;
56                 private CallingConventions callingConvention;
57                 private Module module;
58                 private bool skipVisibility;
59                 private bool init_locals = true;
60                 private ILGenerator ilgen;
61                 private int nrefs;
62                 private object[] refs;
63                 private IntPtr referenced_by;
64                 private Type owner;
65                 #endregion
66 #pragma warning restore 169, 414, 649
67                 
68                 private Delegate deleg;
69                 private MonoMethod method;
70                 private ParameterBuilder[] pinfo;
71                 internal bool creating;
72                 private DynamicILInfo il_info;
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                         if (owner != null && (owner.IsArray || owner.IsInterface)) {
117                                 throw new ArgumentException ("Owner can't be an array or an interface.");
118                         }
119
120                         if (m == null)
121                                 m = AnonHostModuleHolder.AnonHostModule;
122
123                         this.name = name;
124                         this.attributes = attributes | MethodAttributes.Static;
125                         this.callingConvention = callingConvention;
126                         this.returnType = returnType;
127                         this.parameters = parameterTypes;
128                         this.owner = owner;
129                         this.module = m;
130                         this.skipVisibility = skipVisibility;
131                 }
132
133                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
134                 private extern void create_dynamic_method (DynamicMethod m);
135
136                 private void CreateDynMethod () {
137                         if (mhandle.Value == IntPtr.Zero) {
138                                 if (ilgen == null || ilgen.ILOffset == 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                 [ComVisible (true)]
165                 public Delegate CreateDelegate (Type delegateType)
166                 {
167                         if (delegateType == null)
168                                 throw new ArgumentNullException ("delegateType");
169                         if (deleg != null)
170                                 return deleg;
171
172                         CreateDynMethod ();
173
174                         deleg = Delegate.CreateDelegate (delegateType, this);
175                         return deleg;
176                 }
177
178                 [ComVisible (true)]
179                 public Delegate CreateDelegate (Type delegateType, object target)
180                 {
181                         if (delegateType == null)
182                                 throw new ArgumentNullException ("delegateType");
183
184                         CreateDynMethod ();
185
186                         /* Can't cache the delegate since it is different for each target */
187                         return Delegate.CreateDelegate (delegateType, target, this);
188                 }
189                 
190                 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName)
191                 {
192                         //
193                         // Extension: Mono allows position == 0 for the return attribute
194                         //
195                         if ((position < 0) || (position > parameters.Length))
196                                 throw new ArgumentOutOfRangeException ("position");
197
198                         RejectIfCreated ();
199
200                         ParameterBuilder pb = new ParameterBuilder (this, position, attributes, parameterName);
201                         if (pinfo == null)
202                                 pinfo = new ParameterBuilder [parameters.Length + 1];
203                         pinfo [position] = pb;
204                         return pb;
205                 }
206
207                 public override MethodInfo GetBaseDefinition () {
208                         return this;
209                 }
210
211                 [MonoTODO("Not implemented")]
212                 public override object[] GetCustomAttributes (bool inherit) {
213                         throw new NotImplementedException ();
214                 }
215
216                 [MonoTODO("Not implemented")]
217                 public override object[] GetCustomAttributes (Type attributeType,
218                                                                                                           bool inherit) {
219                         throw new NotImplementedException ();
220                 }
221
222                 public DynamicILInfo GetDynamicILInfo () {
223                         if (il_info == null)
224                                 il_info = new DynamicILInfo (this);
225                         return il_info;
226                 }
227
228                 public ILGenerator GetILGenerator () {
229                         return GetILGenerator (64);
230                 }
231
232                 public ILGenerator GetILGenerator (int streamSize) {
233                         if (((GetMethodImplementationFlags () & MethodImplAttributes.CodeTypeMask) != 
234                                  MethodImplAttributes.IL) ||
235                                 ((GetMethodImplementationFlags () & MethodImplAttributes.ManagedMask) != 
236                                  MethodImplAttributes.Managed))
237                                 throw new InvalidOperationException ("Method body should not exist.");
238                         if (ilgen != null)
239                                 return ilgen;
240                         ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), streamSize);
241                         return ilgen;
242                 }               
243
244                 public override MethodImplAttributes GetMethodImplementationFlags () {
245                         return MethodImplAttributes.IL | MethodImplAttributes.Managed;
246                 }
247
248                 public override ParameterInfo[] GetParameters () {
249                         if (parameters == null)
250                                 return new ParameterInfo [0];
251
252                         ParameterInfo[] retval = new ParameterInfo [parameters.Length];
253                         for (int i = 0; i < parameters.Length; i++) {
254                                 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
255                         }
256                         return retval;
257                 }
258                 
259                 internal override int GetParameterCount ()
260                 {
261                         return parameters == null ? 0 : parameters.Length;
262                 }               
263
264                 internal override Type GetParameterType (int pos) {
265                         return parameters [pos];
266                 }
267
268                 /*
269                 public override object Invoke (object obj, object[] parameters) {
270                         CreateDynMethod ();
271                         if (method == null)
272                                 method = new MonoMethod (mhandle);
273                         return method.Invoke (obj, parameters);
274                 }
275                 */
276
277                 public override object Invoke (object obj, BindingFlags invokeAttr,
278                                                                            Binder binder, object[] parameters,
279                                                                            CultureInfo culture)
280                 {
281                         try {
282                                 CreateDynMethod ();
283                                 if (method == null)
284                                         method = new MonoMethod (mhandle);
285
286                                 return method.Invoke (obj, parameters);
287                         }
288                         catch (MethodAccessException mae) {
289                                 throw new TargetInvocationException ("Method cannot be invoked.", mae);
290                         }
291                 }
292
293                 [MonoTODO("Not implemented")]
294                 public override bool IsDefined (Type attributeType, bool inherit) {
295                         throw new NotImplementedException ();
296                 }
297
298                 public override string ToString () {
299                         string parms = String.Empty;
300                         ParameterInfo[] p = GetParameters ();
301                         for (int i = 0; i < p.Length; ++i) {
302                                 if (i > 0)
303                                         parms = parms + ", ";
304                                 parms = parms + p [i].ParameterType.Name;
305                         }
306                         return ReturnType.Name+" "+Name+"("+parms+")";
307                 }
308
309                 public override MethodAttributes Attributes {
310                         get {
311                                 return attributes;
312                         }
313                 }
314
315                 public override CallingConventions CallingConvention {
316                         get {
317                                 return callingConvention;
318                         }
319                 }
320
321                 public override Type DeclaringType {
322                         get {
323                                 return null;
324                         }
325                 }
326
327                 public bool InitLocals {
328                         get {
329                                 return init_locals;
330                         }
331                         set {
332                                 init_locals = value;
333                         }
334                 }
335
336                 public override RuntimeMethodHandle MethodHandle {
337                         get {
338                                 return mhandle;
339                         }
340                 }
341
342                 public override Module Module {
343                         get {
344                                 return module;
345                         }
346                 }
347
348                 public override string Name {
349                         get {
350                                 return name;
351                         }
352                 }
353
354                 public override Type ReflectedType {
355                         get {
356                                 return null;
357                         }
358                 }
359
360                 [MonoTODO("Not implemented")]
361                 public override ParameterInfo ReturnParameter {
362                         get {
363                                 throw new NotImplementedException ();
364                         }
365                 }
366
367                 public override Type ReturnType {
368                         get {
369                                 return returnType;
370                         }
371                 }
372
373                 [MonoTODO("Not implemented")]
374                 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
375                         get {
376                                 throw new NotImplementedException ();
377                         }
378                 }
379
380 /*
381                 public override int MetadataToken {
382                         get {
383                                 return 0;
384                         }
385                 }
386 */
387
388                 private void RejectIfCreated () {
389                         if (mhandle.Value != IntPtr.Zero)
390                                 throw new InvalidOperationException ("Type definition of the method is complete.");
391                 }
392
393                 internal int AddRef (object reference) {
394                         if (refs == null)
395                                 refs = new object [4];
396                         if (nrefs >= refs.Length - 1) {
397                                 object [] new_refs = new object [refs.Length * 2];
398                                 System.Array.Copy (refs, new_refs, refs.Length);
399                                 refs = new_refs;
400                         }
401                         refs [nrefs] = reference;
402                         /* Reserved by the runtime */
403                         refs [nrefs + 1] = null;
404                         nrefs += 2;
405                         return nrefs - 1;
406                 }
407
408                 // This class takes care of constructing the module in a thread safe manner
409                 class AnonHostModuleHolder {
410                         public static Module anon_host_module;
411
412                         static AnonHostModuleHolder () {
413                                 AssemblyName aname = new AssemblyName ();
414                                 aname.Name = "Anonymously Hosted DynamicMethods Assembly";
415                                 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);
416
417                                 anon_host_module = ab.GetManifestModule ();
418                         }
419
420                         public static Module AnonHostModule {
421                                 get {
422                                         return anon_host_module;
423                                 }
424                         }
425                 }
426         }
427
428         internal class DynamicMethodTokenGenerator : TokenGenerator {
429
430                 private DynamicMethod m;
431
432                 public DynamicMethodTokenGenerator (DynamicMethod m) {
433                         this.m = m;
434                 }
435
436                 public int GetToken (string str) {
437                         return m.AddRef (str);
438                 }
439
440                 public int GetToken (MethodInfo method, Type[] opt_param_types) {
441                         throw new InvalidOperationException ();
442                 }
443
444                 public int GetToken (MemberInfo member, bool create_open_instance) {
445                         return m.AddRef (member);
446                 }
447
448                 public int GetToken (SignatureHelper helper) {
449                         return m.AddRef (helper);
450                 }
451         }
452 }
453
454 #endif