* MethodBuilder.cs: In CreateMethodBody, throw ArgumentOutOfRangeException
[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 using System.Diagnostics.SymbolStore;
42
43 namespace System.Reflection.Emit {
44 #if NET_2_0
45         [ComVisible (true)]
46         [ClassInterfaceAttribute (ClassInterfaceType.None)]
47         [ComDefaultInterfaceAttribute (typeof (_MethodBuilder))]
48 #endif
49         public sealed class MethodBuilder : MethodInfo {
50                 private RuntimeMethodHandle mhandle;
51                 private Type rtype;
52                 private Type[] parameters;
53                 private MethodAttributes attrs;
54                 private MethodImplAttributes iattrs;
55                 private string name;
56                 private int table_idx;
57                 private byte[] code;
58                 private ILGenerator ilgen;
59                 private TypeBuilder type;
60                 private ParameterBuilder[] pinfo;
61                 private CustomAttributeBuilder[] cattrs;
62                 private MethodInfo override_method;
63                 private string pi_dll;
64                 private string pi_entry;
65                 private CharSet charset;
66                 private uint extra_flags; /* this encodes set_last_error etc */
67                 private CallingConvention native_cc;
68                 private CallingConventions call_conv;
69                 private bool init_locals = true;
70                 private IntPtr generic_container;
71 #if NET_2_0 || BOOTSTRAP_NET_2_0
72                 private GenericTypeParameterBuilder[] generic_params;
73 #else
74                 private Object generic_params; /* so offsets are the same */
75 #endif
76                 private Type[] returnModReq;
77                 private Type[] returnModOpt;
78                 private Type[][] paramModReq;
79                 private Type[][] paramModOpt;
80                 private RefEmitPermissionSet[] permissions;
81
82                 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) {
83                         this.name = name;
84                         this.attrs = attributes;
85                         this.call_conv = callingConvention;
86                         this.rtype = returnType;
87                         this.returnModReq = returnModReq;
88                         this.returnModOpt = returnModOpt;
89                         this.paramModReq = paramModReq;
90                         this.paramModOpt = paramModOpt;
91                         // The MSDN docs does not specify this, but the MS MethodBuilder
92                         // appends a HasThis flag if the method is not static
93                         if ((attributes & MethodAttributes.Static) == 0)
94                                 this.call_conv |= CallingConventions.HasThis;
95                         if (parameterTypes != null) {
96                                 for (int i = 0; i < parameterTypes.Length; ++i)
97                                         if (parameterTypes [i] == null)
98                                                 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
99
100                                 this.parameters = new Type [parameterTypes.Length];
101                                 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
102                         }
103                         type = tb;
104                         table_idx = get_next_table_index (this, 0x06, true);
105                         //Console.WriteLine ("index for "+name+" set to "+table_idx.ToString());
106                 }
107
108                 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, 
109                                                                 CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt, 
110                         String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset) 
111                         : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt) {
112                         pi_dll = dllName;
113                         pi_entry = entryName;
114                         native_cc = nativeCConv;
115                         charset = nativeCharset;
116                 }
117
118                 public bool InitLocals {
119                         get {return init_locals;}
120                         set {init_locals = value;}
121                 }
122
123                 internal TypeBuilder TypeBuilder {
124                         get {return type;}
125                 }
126
127                 public override RuntimeMethodHandle MethodHandle {
128                         get {
129                                 throw NotSupported ();
130                         }
131                 }
132
133                 public override Type ReturnType {get {return rtype;}}
134                 public override Type ReflectedType {get {return type;}}
135                 public override Type DeclaringType {get {return type;}}
136                 public override string Name {get {return name;}}
137                 public override MethodAttributes Attributes {get {return attrs;}}
138                 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
139                         get {return null;}
140                 }
141
142                 public override CallingConventions CallingConvention { 
143                         get { return call_conv; }
144                 }
145
146                 [MonoTODO]
147                 public string Signature {
148                         get {
149                                 throw new NotImplementedException ();
150                         }
151                 }
152
153                 /* Used by mcs */
154                 internal bool BestFitMapping {
155                         set {
156                                 extra_flags = (uint) ((extra_flags & ~0x30) | (value ? 0x10 : 0x20));
157                         }
158                 }
159
160                 /* Used by mcs */
161                 internal bool ThrowOnUnmappableChar {
162                         set {
163                                 extra_flags = (uint) ((extra_flags & ~0x3000) | (value ? 0x1000 : 0x2000));
164                         }
165                 }
166
167                 /* Used by mcs */
168                 internal bool ExactSpelling {
169                         set {
170                                 extra_flags = (uint) ((extra_flags & ~0x01) | (value ? 0x01 : 0x00));
171                         }
172                 }
173
174                 /* Used by mcs */
175                 internal bool SetLastError {
176                         set {
177                                 extra_flags = (uint) ((extra_flags & ~0x40) | (value ? 0x40 : 0x00));
178                         }
179                 }
180
181                 public MethodToken GetToken() {
182                         return new MethodToken(0x06000000 | table_idx);
183                 }
184                 
185                 public override MethodInfo GetBaseDefinition() {
186                         return this;
187                 }
188                 public override MethodImplAttributes GetMethodImplementationFlags() {
189                         return iattrs;
190                 }
191                 public override ParameterInfo[] GetParameters() {
192                         if (!type.is_created)
193                                 throw NotSupported ();
194                         if (parameters == null)
195                                 return null;
196
197                         ParameterInfo[] retval = new ParameterInfo [parameters.Length];
198                         for (int i = 0; i < parameters.Length; i++) {
199                                 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
200                         }
201                         return retval;
202                 }
203                 
204                 internal override int GetParameterCount ()
205                 {
206                         if (parameters == null)
207                                 return 0;
208                         
209                         return parameters.Length;
210                 }
211
212                 public Module GetModule () {
213                         return type.Module;
214                 }
215
216                 public void CreateMethodBody( byte[] il, int count) {
217                         if ((il != null) && ((count < 0) || (count > il.Length)))
218                                 throw new ArgumentOutOfRangeException ("Index was out of range.  Must be non-negative and less than the size of the collection.");
219
220                         if ((code != null) || type.is_created)
221                                 throw new InvalidOperationException ("Type definition of the method is complete.");
222
223                         if (il == null)
224                                 code = null;
225                         else {
226                                 code = new byte [count];
227                                 System.Array.Copy(il, code, count);
228                         }
229                 }
230
231                 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
232                         throw NotSupported ();
233                 }
234                 public override bool IsDefined (Type attribute_type, bool inherit) {
235                         throw NotSupported ();
236                 }
237                 public override object[] GetCustomAttributes( bool inherit) {
238                         throw NotSupported ();
239                 }
240                 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
241                         throw NotSupported ();
242                 }
243                 public ILGenerator GetILGenerator () {
244                         return GetILGenerator (64);
245                 }
246
247                 public ILGenerator GetILGenerator (int size) {
248                         if (((iattrs & MethodImplAttributes.CodeTypeMask) != 
249                                  MethodImplAttributes.IL) ||
250                                 ((iattrs & MethodImplAttributes.ManagedMask) != 
251                                  MethodImplAttributes.Managed))
252                                 throw new InvalidOperationException ("Method body should not exist.");
253                         if (ilgen != null)
254                                 return ilgen;
255                         ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
256                         return ilgen;
257                 }
258                 
259                 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
260                 {
261                         RejectIfCreated ();
262                         
263                         //
264                         // Extension: Mono allows position == 0 for the return attribute
265                         //
266                         if ((position < 0) || (position > parameters.Length))
267                                 throw new ArgumentOutOfRangeException ("position");
268
269                         ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
270                         if (pinfo == null)
271                                 pinfo = new ParameterBuilder [parameters.Length + 1];
272                         pinfo [position] = pb;
273                         return pb;
274                 }
275
276                 internal void fixup () {
277                         if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
278 #if NET_2_0
279                                 // do not allow zero length method body on MS.NET 2.0 (and higher)
280                                 if (((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0)) && (code == null || code.Length == 0))
281 #else
282                                 if (((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0)) && (code == null))
283 #endif
284                                         throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
285                         }
286                         if (ilgen != null)
287                                 ilgen.label_fixup ();
288                 }
289                 
290                 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
291                 {
292                         if (ilgen != null && ilgen.HasDebugInfo) {
293                                 SymbolToken token = new SymbolToken (GetToken().Token);
294                                 symbolWriter.OpenMethod (token);
295                                 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
296                                 ilgen.GenerateDebugInfo (symbolWriter);
297                                 symbolWriter.CloseMethod ();
298                         }
299                 }
300
301                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
302                         if (customBuilder == null)
303                                 throw new ArgumentNullException ("customBuilder");
304                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
305                         if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
306                                 byte[] data = customBuilder.Data;
307                                 int impla; // the (stupid) ctor takes a short or an int ... 
308                                 impla = (int)data [2];
309                                 impla |= ((int)data [3]) << 8;
310                                 SetImplementationFlags ((MethodImplAttributes)impla);
311                                 return;
312                         }
313                         if (attrname == "System.Runtime.InteropServices.DllImportAttribute") {
314                                 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
315                                 bool preserveSig = true;
316
317                                 /*
318                                  * It would be easier to construct a DllImportAttribute from
319                                  * the custom attribute builder, but the DllImportAttribute 
320                                  * does not contain all the information required here, ie.
321                                  * - some parameters, like BestFitMapping has three values
322                                  *   ("on", "off", "missing"), but DllImportAttribute only
323                                  *   contains two (on/off).
324                                  * - PreserveSig is true by default, while it is false by
325                                  *   default in DllImportAttribute.
326                                  */
327
328                                 pi_dll = (string)attr.ctorArgs [0];
329                                 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
330
331                                 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
332                                         string name = attr.namedParamNames [i];
333                                         object value = attr.namedParamValues [i];
334
335                                         if (name == "CallingConvention")
336                                                 native_cc = (CallingConvention)value;
337                                         else if (name == "CharSet")
338                                                 charset = (CharSet)value;
339                                         else if (name == "EntryPoint")
340                                                 pi_entry = (string)value;
341                                         else if (name == "ExactSpelling")
342                                                 ExactSpelling = (bool)value;
343                                         else if (name == "SetLastError")
344                                                 SetLastError = (bool)value;
345                                         else if (name == "PreserveSig")
346                                                 preserveSig = (bool)value;
347 #if NET_1_1
348                                         else if (name == "BestFitMapping")
349                                                 BestFitMapping = (bool)value;
350                                         else if (name == "ThrowOnUnmappableChar")
351                                                 ThrowOnUnmappableChar = (bool)value;
352 #endif
353                                 }
354
355                                 attrs |= MethodAttributes.PinvokeImpl;
356                                 if (preserveSig)
357                                         iattrs |= MethodImplAttributes.PreserveSig;
358                                 return;
359                         }
360                         if (cattrs != null) {
361                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
362                                 cattrs.CopyTo (new_array, 0);
363                                 new_array [cattrs.Length] = customBuilder;
364                                 cattrs = new_array;
365                         } else {
366                                 cattrs = new CustomAttributeBuilder [1];
367                                 cattrs [0] = customBuilder;
368                         }
369                 }
370
371 #if NET_2_0
372                 [ComVisible (true)]
373 #endif
374                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
375                         if (con == null)
376                                 throw new ArgumentNullException ("con");
377                         if (binaryAttribute == null)
378                                 throw new ArgumentNullException ("binaryAttribute");
379                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
380                 }
381                 public void SetImplementationFlags( MethodImplAttributes attributes) {
382                         RejectIfCreated ();
383                         iattrs = attributes;
384                 }
385
386                 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
387                         if (pset == null)
388                                 throw new ArgumentNullException ("pset");
389                         if ((action == SecurityAction.RequestMinimum) ||
390                                 (action == SecurityAction.RequestOptional) ||
391                                 (action == SecurityAction.RequestRefuse))
392                                 throw new ArgumentException ("Request* values are not permitted", "action");
393
394                         RejectIfCreated ();
395
396                         if (permissions != null) {
397                                 /* Check duplicate actions */
398                                 foreach (RefEmitPermissionSet set in permissions)
399                                         if (set.action == action)
400                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
401
402                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
403                                 permissions.CopyTo (new_array, 0);
404                                 permissions = new_array;
405                         }
406                         else
407                                 permissions = new RefEmitPermissionSet [1];
408
409                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
410                         attrs |= MethodAttributes.HasSecurity;
411                 }
412
413 #if NET_2_0
414                 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
415 #endif
416                 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
417                 {
418                         RejectIfCreated ();
419                         throw new NotImplementedException ();
420                 }
421
422                 [MonoTODO]
423                 public void SetSymCustomAttribute (string name, byte[] data)
424                 {
425                         RejectIfCreated ();
426                         throw new NotImplementedException ();
427                 }
428
429                 public override string ToString()
430                 {
431                         return "MethodBuilder [" + type.Name + "::" + name + "]";
432                 }
433
434                 [MonoTODO]
435                 public override bool Equals (object obj)
436                 {
437                         return base.Equals (obj);
438                 }
439
440                 public override int GetHashCode ()
441                 {
442                         return name.GetHashCode ();
443                 }
444
445                 internal override int get_next_table_index (object obj, int table, bool inc) {
446                         return type.get_next_table_index (obj, table, inc);
447                 }
448
449                 internal void set_override (MethodInfo mdecl) {
450                         override_method = mdecl;
451                 }
452
453                 private void RejectIfCreated () {
454                         if (type.is_created)
455                                 throw new InvalidOperationException ("Type definition of the method is complete.");
456                 }
457
458                 private Exception NotSupported () {
459                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
460                 }
461
462 #if NET_2_0 || BOOTSTRAP_NET_2_0
463                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
464                 public override extern MethodInfo BindGenericParameters (Type [] types);
465
466                 public override bool Mono_IsInflatedMethod {
467                         get {
468                                 return false;
469                         }
470                 }
471
472                 public override bool HasGenericParameters {
473                         get {
474                                 return generic_params != null;
475                         }
476                 }
477
478                 public override Type[] GetGenericArguments ()
479                 {
480                         if (generic_params == null)
481                                 return new Type [0];
482
483                         Type[] result = new Type [generic_params.Length];
484                         for (int i = 0; i < generic_params.Length; i++)
485                                 result [i] = generic_params [i];
486
487                         return result;
488                 }
489
490                 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
491                 {
492                         generic_params = new GenericTypeParameterBuilder [names.Length];
493                         for (int i = 0; i < names.Length; i++)
494                                 generic_params [i] = new GenericTypeParameterBuilder (
495                                         type, this, names [i], i);
496
497                         return generic_params;
498                 }
499
500                 public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
501                 {
502                         RejectIfCreated ();
503
504                         this.attrs = attributes;
505                         this.call_conv = callingConvention;
506                         if ((attributes & MethodAttributes.Static) == 0)
507                                 this.call_conv |= CallingConventions.HasThis;
508
509                         this.rtype = return_type;
510                         this.parameters = new Type [parameter_types.Length];
511                         System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
512                 }
513
514                 public void SetReturnType (Type returnType)
515                 {
516                         rtype = returnType;
517                 }
518
519                 public void SetParameters (params Type[] parameterTypes)
520                 {
521                         if (parameterTypes != null) {
522                                 for (int i = 0; i < parameterTypes.Length; ++i)
523                                         if (parameterTypes [i] == null)
524                                                 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
525
526                                 this.parameters = new Type [parameterTypes.Length];
527                                 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
528                         }
529                 }
530
531                 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
532                         SetReturnType (returnType);
533                         SetParameters (parameterTypes);
534                         this.returnModReq = returnTypeRequiredCustomModifiers;
535                         this.returnModOpt = returnTypeOptionalCustomModifiers;
536                         this.paramModReq = parameterTypeRequiredCustomModifiers;
537                         this.paramModOpt = parameterTypeOptionalCustomModifiers;
538                 }
539
540                 public override Module Module {
541                         get {
542                                 return base.Module;
543                         }
544                 }
545 #endif
546         }
547 }
548