2 // System.Reflection.Emit/MethodBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
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.
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;
43 namespace System.Reflection.Emit {
46 [ClassInterfaceAttribute (ClassInterfaceType.None)]
47 [ComDefaultInterfaceAttribute (typeof (_MethodBuilder))]
49 public sealed class MethodBuilder : MethodInfo {
50 private RuntimeMethodHandle mhandle;
52 private Type[] parameters;
53 private MethodAttributes attrs;
54 private MethodImplAttributes iattrs;
56 private int table_idx;
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;
74 private Object generic_params; /* so offsets are the same */
76 private Type[] returnModReq;
77 private Type[] returnModOpt;
78 private Type[][] paramModReq;
79 private Type[][] paramModOpt;
80 private RefEmitPermissionSet[] permissions;
82 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) {
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");
100 this.parameters = new Type [parameterTypes.Length];
101 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
104 table_idx = get_next_table_index (this, 0x06, true);
105 //Console.WriteLine ("index for "+name+" set to "+table_idx.ToString());
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) {
113 pi_entry = entryName;
114 native_cc = nativeCConv;
115 charset = nativeCharset;
118 public bool InitLocals {
119 get {return init_locals;}
120 set {init_locals = value;}
123 internal TypeBuilder TypeBuilder {
127 public override RuntimeMethodHandle MethodHandle {
129 throw NotSupported ();
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 {
142 public override CallingConventions CallingConvention {
143 get { return call_conv; }
147 public string Signature {
149 throw new NotImplementedException ();
154 internal bool BestFitMapping {
156 extra_flags = (uint) ((extra_flags & ~0x30) | (value ? 0x10 : 0x20));
161 internal bool ThrowOnUnmappableChar {
163 extra_flags = (uint) ((extra_flags & ~0x3000) | (value ? 0x1000 : 0x2000));
168 internal bool ExactSpelling {
170 extra_flags = (uint) ((extra_flags & ~0x01) | (value ? 0x01 : 0x00));
175 internal bool SetLastError {
177 extra_flags = (uint) ((extra_flags & ~0x40) | (value ? 0x40 : 0x00));
181 public MethodToken GetToken() {
182 return new MethodToken(0x06000000 | table_idx);
185 public override MethodInfo GetBaseDefinition() {
188 public override MethodImplAttributes GetMethodImplementationFlags() {
191 public override ParameterInfo[] GetParameters() {
192 if (!type.is_created)
193 throw NotSupported ();
194 if (parameters == null)
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);
204 internal override int GetParameterCount ()
206 if (parameters == null)
209 return parameters.Length;
212 public Module GetModule () {
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.");
220 if ((code != null) || type.is_created)
221 throw new InvalidOperationException ("Type definition of the method is complete.");
226 code = new byte [count];
227 System.Array.Copy(il, code, count);
231 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
232 throw NotSupported ();
234 public override bool IsDefined (Type attribute_type, bool inherit) {
235 throw NotSupported ();
237 public override object[] GetCustomAttributes( bool inherit) {
238 throw NotSupported ();
240 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
241 throw NotSupported ();
243 public ILGenerator GetILGenerator () {
244 return GetILGenerator (64);
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.");
255 ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
259 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
264 // Extension: Mono allows position == 0 for the return attribute
266 if ((position < 0) || (position > parameters.Length))
267 throw new ArgumentOutOfRangeException ("position");
269 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
271 pinfo = new ParameterBuilder [parameters.Length + 1];
272 pinfo [position] = pb;
276 internal void fixup () {
277 if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 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))
282 if (((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0)) && (code == null))
284 throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
287 ilgen.label_fixup ();
290 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
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 ();
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);
313 if (attrname == "System.Runtime.InteropServices.DllImportAttribute") {
314 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
315 bool preserveSig = true;
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.
328 pi_dll = (string)attr.ctorArgs [0];
329 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
331 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
332 string name = attr.namedParamNames [i];
333 object value = attr.namedParamValues [i];
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;
348 else if (name == "BestFitMapping")
349 BestFitMapping = (bool)value;
350 else if (name == "ThrowOnUnmappableChar")
351 ThrowOnUnmappableChar = (bool)value;
355 attrs |= MethodAttributes.PinvokeImpl;
357 iattrs |= MethodImplAttributes.PreserveSig;
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;
366 cattrs = new CustomAttributeBuilder [1];
367 cattrs [0] = customBuilder;
374 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
376 throw new ArgumentNullException ("con");
377 if (binaryAttribute == null)
378 throw new ArgumentNullException ("binaryAttribute");
379 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
381 public void SetImplementationFlags( MethodImplAttributes attributes) {
386 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
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");
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.");
402 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
403 permissions.CopyTo (new_array, 0);
404 permissions = new_array;
407 permissions = new RefEmitPermissionSet [1];
409 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
410 attrs |= MethodAttributes.HasSecurity;
414 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
416 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
419 throw new NotImplementedException ();
423 public void SetSymCustomAttribute (string name, byte[] data)
426 throw new NotImplementedException ();
429 public override string ToString()
431 return "MethodBuilder [" + type.Name + "::" + name + "]";
435 public override bool Equals (object obj)
437 return base.Equals (obj);
440 public override int GetHashCode ()
442 return name.GetHashCode ();
445 internal override int get_next_table_index (object obj, int table, bool inc) {
446 return type.get_next_table_index (obj, table, inc);
449 internal void set_override (MethodInfo mdecl) {
450 override_method = mdecl;
453 private void RejectIfCreated () {
455 throw new InvalidOperationException ("Type definition of the method is complete.");
458 private Exception NotSupported () {
459 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
462 #if NET_2_0 || BOOTSTRAP_NET_2_0
463 [MethodImplAttribute(MethodImplOptions.InternalCall)]
464 public override extern MethodInfo BindGenericParameters (Type [] types);
466 public override bool Mono_IsInflatedMethod {
472 public override bool HasGenericParameters {
474 return generic_params != null;
478 public override Type[] GetGenericArguments ()
480 if (generic_params == null)
483 Type[] result = new Type [generic_params.Length];
484 for (int i = 0; i < generic_params.Length; i++)
485 result [i] = generic_params [i];
490 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
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);
497 return generic_params;
500 public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
504 this.attrs = attributes;
505 this.call_conv = callingConvention;
506 if ((attributes & MethodAttributes.Static) == 0)
507 this.call_conv |= CallingConventions.HasThis;
509 this.rtype = return_type;
510 this.parameters = new Type [parameter_types.Length];
511 System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
514 public void SetReturnType (Type returnType)
519 public void SetParameters (params Type[] parameterTypes)
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");
526 this.parameters = new Type [parameterTypes.Length];
527 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
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;
540 public override Module Module {