This commit was manufactured by cvs2svn to create branch 'mono-1-0'.
[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 #if NET_2_0 || BOOTSTRAP_NET_2_0
65                 private GenericTypeParameterBuilder[] generic_params;
66 #else
67                 private Object generic_params; /* so offsets are the same */
68 #endif
69                 private Type[] returnModReq;
70                 private Type[] returnModOpt;
71                 private Type[][] paramModReq;
72                 private Type[][] paramModOpt;
73                 private RefEmitPermissionSet[] permissions;
74
75                 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) {
76                         this.name = name;
77                         this.attrs = attributes;
78                         this.call_conv = callingConvention;
79                         this.rtype = returnType;
80                         this.returnModReq = returnModReq;
81                         this.returnModOpt = returnModOpt;
82                         this.paramModReq = paramModReq;
83                         this.paramModOpt = paramModOpt;
84                         // The MSDN docs does not specify this, but the MS MethodBuilder
85                         // appends a HasThis flag if the method is not static
86                         if ((attributes & MethodAttributes.Static) == 0)
87                                 this.call_conv |= CallingConventions.HasThis;
88                         if (parameterTypes != null) {
89                                 this.parameters = new Type [parameterTypes.Length];
90                                 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
91                         }
92                         type = tb;
93                         table_idx = get_next_table_index (this, 0x06, true);
94                         //Console.WriteLine ("index for "+name+" set to "+table_idx.ToString());
95                 }
96
97                 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, 
98                                                                 CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt, 
99                         String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset) 
100                         : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt) {
101                         pi_dll = dllName;
102                         pi_entry = entryName;
103                         native_cc = nativeCConv;
104                         ncharset = nativeCharset;
105                 }
106
107                 public bool InitLocals {
108                         get {return init_locals;}
109                         set {init_locals = value;}
110                 }
111
112                 internal TypeBuilder TypeBuilder {
113                         get {return type;}
114                 }
115
116                 public override RuntimeMethodHandle MethodHandle {
117                         get {
118                                 throw NotSupported ();
119                         }
120                 }
121
122                 public override Type ReturnType {get {return rtype;}}
123                 public override Type ReflectedType {get {return type;}}
124                 public override Type DeclaringType {get {return type;}}
125                 public override string Name {get {return name;}}
126                 public override MethodAttributes Attributes {get {return attrs;}}
127                 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
128                         get {return null;}
129                 }
130
131                 public override CallingConventions CallingConvention { 
132                         get { return call_conv; }
133                 }
134
135                 [MonoTODO]
136                 public string Signature {
137                         get {
138                                 throw new NotImplementedException ();
139                         }
140                 }
141
142                 public MethodToken GetToken() {
143                         return new MethodToken(0x06000000 | table_idx);
144                 }
145                 
146                 public override MethodInfo GetBaseDefinition() {
147                         return this;
148                 }
149                 public override MethodImplAttributes GetMethodImplementationFlags() {
150                         return iattrs;
151                 }
152                 public override ParameterInfo[] GetParameters() {
153                         if (parameters == null)
154                                 return null;
155
156                         ParameterInfo[] retval = new ParameterInfo [parameters.Length];
157                         for (int i = 0; i < parameters.Length; i++) {
158                                 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
159                         }
160                         return retval;
161                 }
162                 
163                 internal override int GetParameterCount ()
164                 {
165                         if (parameters == null)
166                                 return 0;
167                         
168                         return parameters.Length;
169                 }
170
171                 public Module GetModule () {
172                         return type.Module;
173                 }
174
175                 public void CreateMethodBody( byte[] il, int count) {
176                         if ((il != null) && ((count < 0) || (count > il.Length)))
177                                 throw new ArgumentException ("Index was out of range.  Must be non-negative and less than the size of the collection.");
178
179                         if ((code != null) || type.is_created)
180                                 throw new InvalidOperationException ("Type definition of the method is complete.");
181
182                         if (il == null)
183                                 code = null;
184                         else {
185                                 code = new byte [count];
186                                 System.Array.Copy(il, code, count);
187                         }
188                 }
189
190                 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
191                         throw NotSupported ();
192                 }
193                 public override bool IsDefined (Type attribute_type, bool inherit) {
194                         throw NotSupported ();
195                 }
196                 public override object[] GetCustomAttributes( bool inherit) {
197                         throw NotSupported ();
198                 }
199                 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
200                         throw NotSupported ();
201                 }
202                 public ILGenerator GetILGenerator () {
203                         return GetILGenerator (64);
204                 }
205
206                 public ILGenerator GetILGenerator (int size) {
207                         if (((iattrs & MethodImplAttributes.CodeTypeMask) != 
208                                  MethodImplAttributes.IL) ||
209                                 ((iattrs & MethodImplAttributes.ManagedMask) != 
210                                  MethodImplAttributes.Managed))
211                                 throw new InvalidOperationException ("Method body should not exist.");
212                         if (ilgen != null)
213                                 return ilgen;
214                         ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
215                         return ilgen;
216                 }
217                 
218                 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
219                 {
220                         RejectIfCreated ();
221                         
222                         //
223                         // Extension: Mono allows position == 0 for the return attribute
224                         //
225                         if ((position < 0) || (position > parameters.Length))
226                                 throw new ArgumentOutOfRangeException ("position");
227
228                         ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
229                         if (pinfo == null)
230                                 pinfo = new ParameterBuilder [parameters.Length + 1];
231                         pinfo [position] = pb;
232                         return pb;
233                 }
234
235                 internal void fixup () {
236                         if (ilgen != null)
237                                 ilgen.label_fixup ();
238                 }
239
240                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
241                         if (customBuilder == null)
242                                 throw new ArgumentNullException ("customBuilder");
243                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
244                         if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
245                                 byte[] data = customBuilder.Data;
246                                 int impla; // the (stupid) ctor takes a short or an int ... 
247                                 impla = (int)data [2];
248                                 impla |= ((int)data [3]) << 8;
249                                 SetImplementationFlags ((MethodImplAttributes)impla);
250                                 return;
251                         }
252                         if (cattrs != null) {
253                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
254                                 cattrs.CopyTo (new_array, 0);
255                                 new_array [cattrs.Length] = customBuilder;
256                                 cattrs = new_array;
257                         } else {
258                                 cattrs = new CustomAttributeBuilder [1];
259                                 cattrs [0] = customBuilder;
260                         }
261                 }
262                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
263                         if (con == null)
264                                 throw new ArgumentNullException ("con");
265                         if (binaryAttribute == null)
266                                 throw new ArgumentNullException ("binaryAttribute");
267                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
268                 }
269                 public void SetImplementationFlags( MethodImplAttributes attributes) {
270                         RejectIfCreated ();
271                         iattrs = attributes;
272                 }
273
274                 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
275                         if (pset == null)
276                                 throw new ArgumentNullException ("pset");
277                         if ((action == SecurityAction.RequestMinimum) ||
278                                 (action == SecurityAction.RequestOptional) ||
279                                 (action == SecurityAction.RequestRefuse))
280                                 throw new ArgumentException ("Request* values are not permitted", "action");
281
282                         RejectIfCreated ();
283
284                         if (permissions != null) {
285                                 /* Check duplicate actions */
286                                 foreach (RefEmitPermissionSet set in permissions)
287                                         if (set.action == action)
288                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
289
290                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
291                                 permissions.CopyTo (new_array, 0);
292                                 permissions = new_array;
293                         }
294                         else
295                                 permissions = new RefEmitPermissionSet [1];
296
297                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
298                         attrs |= MethodAttributes.HasSecurity;
299                 }
300
301                 [MonoTODO]
302                 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
303                 {
304                         RejectIfCreated ();
305                         throw new NotImplementedException ();
306                 }
307
308                 [MonoTODO]
309                 public void SetSymCustomAttribute (string name, byte[] data)
310                 {
311                         RejectIfCreated ();
312                         throw new NotImplementedException ();
313                 }
314
315                 public override string ToString()
316                 {
317                         return "MethodBuilder [" + type.Name + "::" + name + "]";
318                 }
319
320                 [MonoTODO]
321                 public override bool Equals (object obj)
322                 {
323                         return base.Equals (obj);
324                 }
325
326                 public override int GetHashCode ()
327                 {
328                         return name.GetHashCode ();
329                 }
330
331                 internal override int get_next_table_index (object obj, int table, bool inc) {
332                         return type.get_next_table_index (obj, table, inc);
333                 }
334
335                 internal void set_override (MethodInfo mdecl) {
336                         override_method = mdecl;
337                 }
338
339                 private void RejectIfCreated () {
340                         if (type.is_created)
341                                 throw new InvalidOperationException ("Type definition of the method is complete.");
342                 }
343
344                 private Exception NotSupported () {
345                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
346                 }
347
348 #if NET_2_0 || BOOTSTRAP_NET_2_0
349                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
350                 public override extern MethodInfo BindGenericParameters (Type [] types);
351
352                 public override bool Mono_IsInflatedMethod {
353                         get {
354                                 return false;
355                         }
356                 }
357
358                 public override bool HasGenericParameters {
359                         get {
360                                 return generic_params != null;
361                         }
362                 }
363
364                 public override Type[] GetGenericArguments ()
365                 {
366                         if (generic_params == null)
367                                 return new Type [0];
368
369                         Type[] result = new Type [generic_params.Length];
370                         for (int i = 0; i < generic_params.Length; i++)
371                                 result [i] = generic_params [i];
372
373                         return result;
374                 }
375
376                 public GenericTypeParameterBuilder[] DefineGenericParameters (string[] names)
377                 {
378                         generic_params = new GenericTypeParameterBuilder [names.Length];
379                         for (int i = 0; i < names.Length; i++)
380                                 generic_params [i] = new GenericTypeParameterBuilder (
381                                         type, this, names [i], i);
382
383                         return generic_params;
384                 }
385
386                 public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
387                 {
388                         RejectIfCreated ();
389
390                         this.attrs = attributes;
391                         this.call_conv = callingConvention;
392                         if ((attributes & MethodAttributes.Static) == 0)
393                                 this.call_conv |= CallingConventions.HasThis;
394
395                         this.rtype = return_type;
396                         this.parameters = new Type [parameter_types.Length];
397                         System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
398                 }
399 #endif
400         }
401 }
402