2005-01-21 Rafael Teixeira <rafaelteixeirabr@hotmail.com>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / MethodBuilder.cs
1 //
2 // System.Reflection.Emit/MethodBuilder.cs
3 //
4 // Author:
5 //   Paolo Molaro (lupus@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.  http://www.ximian.com
8 //
9
10 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System;
34 using System.Reflection;
35 using System.Reflection.Emit;
36 using System.Globalization;
37 using System.Security;
38 using System.Security.Permissions;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41
42 namespace System.Reflection.Emit {
43
44         public sealed class MethodBuilder : MethodInfo {
45                 private RuntimeMethodHandle mhandle;
46                 private Type rtype;
47                 private Type[] parameters;
48                 private MethodAttributes attrs;
49                 private MethodImplAttributes iattrs;
50                 private string name;
51                 private int table_idx;
52                 private byte[] code;
53                 private ILGenerator ilgen;
54                 private TypeBuilder type;
55                 private ParameterBuilder[] pinfo;
56                 private CustomAttributeBuilder[] cattrs;
57                 private MethodInfo override_method;
58                 private string pi_dll;
59                 private string pi_entry;
60                 private CharSet ncharset;
61                 private CallingConvention native_cc;
62                 private CallingConventions call_conv;
63                 private bool init_locals = true;
64                 private IntPtr generic_container;
65 #if NET_2_0 || BOOTSTRAP_NET_2_0
66                 private GenericTypeParameterBuilder[] generic_params;
67 #else
68                 private Object generic_params; /* so offsets are the same */
69 #endif
70                 private Type[] returnModReq;
71                 private Type[] returnModOpt;
72                 private Type[][] paramModReq;
73                 private Type[][] paramModOpt;
74                 private RefEmitPermissionSet[] permissions;
75
76                 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) {
77                         this.name = name;
78                         this.attrs = attributes;
79                         this.call_conv = callingConvention;
80                         this.rtype = returnType;
81                         this.returnModReq = returnModReq;
82                         this.returnModOpt = returnModOpt;
83                         this.paramModReq = paramModReq;
84                         this.paramModOpt = paramModOpt;
85                         // The MSDN docs does not specify this, but the MS MethodBuilder
86                         // appends a HasThis flag if the method is not static
87                         if ((attributes & MethodAttributes.Static) == 0)
88                                 this.call_conv |= CallingConventions.HasThis;
89                         if (parameterTypes != null) {
90                                 this.parameters = new Type [parameterTypes.Length];
91                                 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
92                         }
93                         type = tb;
94                         table_idx = get_next_table_index (this, 0x06, true);
95                         //Console.WriteLine ("index for "+name+" set to "+table_idx.ToString());
96                 }
97
98                 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, 
99                                                                 CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt, 
100                         String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset) 
101                         : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt) {
102                         pi_dll = dllName;
103                         pi_entry = entryName;
104                         native_cc = nativeCConv;
105                         ncharset = nativeCharset;
106                 }
107
108                 public bool InitLocals {
109                         get {return init_locals;}
110                         set {init_locals = value;}
111                 }
112
113                 internal TypeBuilder TypeBuilder {
114                         get {return type;}
115                 }
116
117                 public override RuntimeMethodHandle MethodHandle {
118                         get {
119                                 throw NotSupported ();
120                         }
121                 }
122
123                 public override Type ReturnType {get {return rtype;}}
124                 public override Type ReflectedType {get {return type;}}
125                 public override Type DeclaringType {get {return type;}}
126                 public override string Name {get {return name;}}
127                 public override MethodAttributes Attributes {get {return attrs;}}
128                 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
129                         get {return null;}
130                 }
131
132                 public override CallingConventions CallingConvention { 
133                         get { return call_conv; }
134                 }
135
136                 [MonoTODO]
137                 public string Signature {
138                         get {
139                                 throw new NotImplementedException ();
140                         }
141                 }
142
143                 public MethodToken GetToken() {
144                         return new MethodToken(0x06000000 | table_idx);
145                 }
146                 
147                 public override MethodInfo GetBaseDefinition() {
148                         return this;
149                 }
150                 public override MethodImplAttributes GetMethodImplementationFlags() {
151                         return iattrs;
152                 }
153                 public override ParameterInfo[] GetParameters() {
154                         if (!type.is_created)
155                                 throw NotSupported ();
156                         if (parameters == null)
157                                 return null;
158
159                         ParameterInfo[] retval = new ParameterInfo [parameters.Length];
160                         for (int i = 0; i < parameters.Length; i++) {
161                                 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
162                         }
163                         return retval;
164                 }
165                 
166                 internal override int GetParameterCount ()
167                 {
168                         if (parameters == null)
169                                 return 0;
170                         
171                         return parameters.Length;
172                 }
173
174                 public Module GetModule () {
175                         return type.Module;
176                 }
177
178                 public void CreateMethodBody( byte[] il, int count) {
179                         if ((il != null) && ((count < 0) || (count > il.Length)))
180                                 throw new ArgumentException ("Index was out of range.  Must be non-negative and less than the size of the collection.");
181
182                         if ((code != null) || type.is_created)
183                                 throw new InvalidOperationException ("Type definition of the method is complete.");
184
185                         if (il == null)
186                                 code = null;
187                         else {
188                                 code = new byte [count];
189                                 System.Array.Copy(il, code, count);
190                         }
191                 }
192
193                 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
194                         throw NotSupported ();
195                 }
196                 public override bool IsDefined (Type attribute_type, bool inherit) {
197                         throw NotSupported ();
198                 }
199                 public override object[] GetCustomAttributes( bool inherit) {
200                         throw NotSupported ();
201                 }
202                 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
203                         throw NotSupported ();
204                 }
205                 public ILGenerator GetILGenerator () {
206                         return GetILGenerator (64);
207                 }
208
209                 public ILGenerator GetILGenerator (int size) {
210                         if (((iattrs & MethodImplAttributes.CodeTypeMask) != 
211                                  MethodImplAttributes.IL) ||
212                                 ((iattrs & MethodImplAttributes.ManagedMask) != 
213                                  MethodImplAttributes.Managed))
214                                 throw new InvalidOperationException ("Method body should not exist.");
215                         if (ilgen != null)
216                                 return ilgen;
217                         ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
218                         return ilgen;
219                 }
220                 
221                 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
222                 {
223                         RejectIfCreated ();
224                         
225                         //
226                         // Extension: Mono allows position == 0 for the return attribute
227                         //
228                         if ((position < 0) || (position > parameters.Length))
229                                 throw new ArgumentOutOfRangeException ("position");
230
231                         ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
232                         if (pinfo == null)
233                                 pinfo = new ParameterBuilder [parameters.Length + 1];
234                         pinfo [position] = pb;
235                         return pb;
236                 }
237
238                 internal void fixup () {
239                         if (ilgen != null)
240                                 ilgen.label_fixup ();
241                 }
242
243                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
244                         if (customBuilder == null)
245                                 throw new ArgumentNullException ("customBuilder");
246                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
247                         if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
248                                 byte[] data = customBuilder.Data;
249                                 int impla; // the (stupid) ctor takes a short or an int ... 
250                                 impla = (int)data [2];
251                                 impla |= ((int)data [3]) << 8;
252                                 SetImplementationFlags ((MethodImplAttributes)impla);
253                                 return;
254                         }
255                         if (cattrs != null) {
256                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
257                                 cattrs.CopyTo (new_array, 0);
258                                 new_array [cattrs.Length] = customBuilder;
259                                 cattrs = new_array;
260                         } else {
261                                 cattrs = new CustomAttributeBuilder [1];
262                                 cattrs [0] = customBuilder;
263                         }
264                 }
265                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
266                         if (con == null)
267                                 throw new ArgumentNullException ("con");
268                         if (binaryAttribute == null)
269                                 throw new ArgumentNullException ("binaryAttribute");
270                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
271                 }
272                 public void SetImplementationFlags( MethodImplAttributes attributes) {
273                         RejectIfCreated ();
274                         iattrs = attributes;
275                 }
276
277                 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
278                         if (pset == null)
279                                 throw new ArgumentNullException ("pset");
280                         if ((action == SecurityAction.RequestMinimum) ||
281                                 (action == SecurityAction.RequestOptional) ||
282                                 (action == SecurityAction.RequestRefuse))
283                                 throw new ArgumentException ("Request* values are not permitted", "action");
284
285                         RejectIfCreated ();
286
287                         if (permissions != null) {
288                                 /* Check duplicate actions */
289                                 foreach (RefEmitPermissionSet set in permissions)
290                                         if (set.action == action)
291                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
292
293                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
294                                 permissions.CopyTo (new_array, 0);
295                                 permissions = new_array;
296                         }
297                         else
298                                 permissions = new RefEmitPermissionSet [1];
299
300                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
301                         attrs |= MethodAttributes.HasSecurity;
302                 }
303
304                 [MonoTODO]
305                 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
306                 {
307                         RejectIfCreated ();
308                         throw new NotImplementedException ();
309                 }
310
311                 [MonoTODO]
312                 public void SetSymCustomAttribute (string name, byte[] data)
313                 {
314                         RejectIfCreated ();
315                         throw new NotImplementedException ();
316                 }
317
318                 public override string ToString()
319                 {
320                         return "MethodBuilder [" + type.Name + "::" + name + "]";
321                 }
322
323                 [MonoTODO]
324                 public override bool Equals (object obj)
325                 {
326                         return base.Equals (obj);
327                 }
328
329                 public override int GetHashCode ()
330                 {
331                         return name.GetHashCode ();
332                 }
333
334                 internal override int get_next_table_index (object obj, int table, bool inc) {
335                         return type.get_next_table_index (obj, table, inc);
336                 }
337
338                 internal void set_override (MethodInfo mdecl) {
339                         override_method = mdecl;
340                 }
341
342                 private void RejectIfCreated () {
343                         if (type.is_created)
344                                 throw new InvalidOperationException ("Type definition of the method is complete.");
345                 }
346
347                 private Exception NotSupported () {
348                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
349                 }
350
351 #if NET_2_0 || BOOTSTRAP_NET_2_0
352                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
353                 public override extern MethodInfo BindGenericParameters (Type [] types);
354
355                 public override bool Mono_IsInflatedMethod {
356                         get {
357                                 return false;
358                         }
359                 }
360
361                 public override bool HasGenericParameters {
362                         get {
363                                 return generic_params != null;
364                         }
365                 }
366
367                 public override Type[] GetGenericArguments ()
368                 {
369                         if (generic_params == null)
370                                 return new Type [0];
371
372                         Type[] result = new Type [generic_params.Length];
373                         for (int i = 0; i < generic_params.Length; i++)
374                                 result [i] = generic_params [i];
375
376                         return result;
377                 }
378
379                 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
380                 {
381                         generic_params = new GenericTypeParameterBuilder [names.Length];
382                         for (int i = 0; i < names.Length; i++)
383                                 generic_params [i] = new GenericTypeParameterBuilder (
384                                         type, this, names [i], i);
385
386                         return generic_params;
387                 }
388
389                 public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
390                 {
391                         RejectIfCreated ();
392
393                         this.attrs = attributes;
394                         this.call_conv = callingConvention;
395                         if ((attributes & MethodAttributes.Static) == 0)
396                                 this.call_conv |= CallingConventions.HasThis;
397
398                         this.rtype = return_type;
399                         this.parameters = new Type [parameter_types.Length];
400                         System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
401                 }
402 #endif
403         }
404 }
405