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 [ComDefaultInterface (typeof (_MethodBuilder))]
48 [ClassInterface (ClassInterfaceType.None)]
49 public sealed class MethodBuilder : MethodInfo, _MethodBuilder {
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) {
239 * On MS.NET, this always returns not_supported, but we can't do this
240 * since there would be no way to obtain custom attributes of
241 * dynamically created ctors.
244 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
246 throw NotSupported ();
249 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
251 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
253 throw NotSupported ();
256 public ILGenerator GetILGenerator () {
257 return GetILGenerator (64);
260 public ILGenerator GetILGenerator (int size) {
261 if (((iattrs & MethodImplAttributes.CodeTypeMask) !=
262 MethodImplAttributes.IL) ||
263 ((iattrs & MethodImplAttributes.ManagedMask) !=
264 MethodImplAttributes.Managed))
265 throw new InvalidOperationException ("Method body should not exist.");
268 ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
272 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
277 // Extension: Mono allows position == 0 for the return attribute
279 if ((position < 0) || (position > parameters.Length))
280 throw new ArgumentOutOfRangeException ("position");
282 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
284 pinfo = new ParameterBuilder [parameters.Length + 1];
285 pinfo [position] = pb;
289 internal void fixup () {
290 if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
292 // do not allow zero length method body on MS.NET 2.0 (and higher)
293 if (((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0)) && (code == null || code.Length == 0))
295 if (((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0)) && (code == null))
297 throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
300 ilgen.label_fixup ();
303 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
305 if (ilgen != null && ilgen.HasDebugInfo) {
306 SymbolToken token = new SymbolToken (GetToken().Token);
307 symbolWriter.OpenMethod (token);
308 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
309 ilgen.GenerateDebugInfo (symbolWriter);
310 symbolWriter.CloseMethod ();
314 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
315 if (customBuilder == null)
316 throw new ArgumentNullException ("customBuilder");
317 string attrname = customBuilder.Ctor.ReflectedType.FullName;
318 if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
319 byte[] data = customBuilder.Data;
320 int impla; // the (stupid) ctor takes a short or an int ...
321 impla = (int)data [2];
322 impla |= ((int)data [3]) << 8;
323 SetImplementationFlags ((MethodImplAttributes)impla);
326 if (attrname == "System.Runtime.InteropServices.DllImportAttribute") {
327 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
328 bool preserveSig = true;
331 * It would be easier to construct a DllImportAttribute from
332 * the custom attribute builder, but the DllImportAttribute
333 * does not contain all the information required here, ie.
334 * - some parameters, like BestFitMapping has three values
335 * ("on", "off", "missing"), but DllImportAttribute only
336 * contains two (on/off).
337 * - PreserveSig is true by default, while it is false by
338 * default in DllImportAttribute.
341 pi_dll = (string)attr.ctorArgs [0];
342 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
344 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
345 string name = attr.namedParamNames [i];
346 object value = attr.namedParamValues [i];
348 if (name == "CallingConvention")
349 native_cc = (CallingConvention)value;
350 else if (name == "CharSet")
351 charset = (CharSet)value;
352 else if (name == "EntryPoint")
353 pi_entry = (string)value;
354 else if (name == "ExactSpelling")
355 ExactSpelling = (bool)value;
356 else if (name == "SetLastError")
357 SetLastError = (bool)value;
358 else if (name == "PreserveSig")
359 preserveSig = (bool)value;
361 else if (name == "BestFitMapping")
362 BestFitMapping = (bool)value;
363 else if (name == "ThrowOnUnmappableChar")
364 ThrowOnUnmappableChar = (bool)value;
368 if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
369 attrs |= MethodAttributes.SpecialName;
374 attrs |= MethodAttributes.PinvokeImpl;
376 iattrs |= MethodImplAttributes.PreserveSig;
379 if (cattrs != null) {
380 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
381 cattrs.CopyTo (new_array, 0);
382 new_array [cattrs.Length] = customBuilder;
385 cattrs = new CustomAttributeBuilder [1];
386 cattrs [0] = customBuilder;
393 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
395 throw new ArgumentNullException ("con");
396 if (binaryAttribute == null)
397 throw new ArgumentNullException ("binaryAttribute");
398 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
400 public void SetImplementationFlags( MethodImplAttributes attributes) {
405 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
407 throw new ArgumentNullException ("pset");
408 if ((action == SecurityAction.RequestMinimum) ||
409 (action == SecurityAction.RequestOptional) ||
410 (action == SecurityAction.RequestRefuse))
411 throw new ArgumentException ("Request* values are not permitted", "action");
415 if (permissions != null) {
416 /* Check duplicate actions */
417 foreach (RefEmitPermissionSet set in permissions)
418 if (set.action == action)
419 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
421 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
422 permissions.CopyTo (new_array, 0);
423 permissions = new_array;
426 permissions = new RefEmitPermissionSet [1];
428 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
429 attrs |= MethodAttributes.HasSecurity;
433 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
435 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
438 throw new NotImplementedException ();
442 public void SetSymCustomAttribute (string name, byte[] data)
445 throw new NotImplementedException ();
448 public override string ToString()
450 return "MethodBuilder [" + type.Name + "::" + name + "]";
454 public override bool Equals (object obj)
456 return base.Equals (obj);
459 public override int GetHashCode ()
461 return name.GetHashCode ();
464 internal override int get_next_table_index (object obj, int table, bool inc) {
465 return type.get_next_table_index (obj, table, inc);
468 internal void set_override (MethodInfo mdecl) {
469 override_method = mdecl;
472 private void RejectIfCreated () {
474 throw new InvalidOperationException ("Type definition of the method is complete.");
477 private Exception NotSupported () {
478 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
481 #if NET_2_0 || BOOTSTRAP_NET_2_0
482 [MethodImplAttribute(MethodImplOptions.InternalCall)]
483 public override extern MethodInfo MakeGenericMethod (Type [] types);
485 public override bool Mono_IsInflatedMethod {
491 public override bool HasGenericParameters {
493 return generic_params != null;
497 public override bool IsGenericMethodDefinition {
499 return HasGenericParameters;
503 public override bool IsGenericMethod {
505 return HasGenericParameters;
509 public override MethodInfo GetGenericMethodDefinition ()
511 if (!IsGenericMethodDefinition)
512 throw new InvalidOperationException ();
517 public override Type[] GetGenericArguments ()
519 if (generic_params == null)
522 Type[] result = new Type [generic_params.Length];
523 for (int i = 0; i < generic_params.Length; i++)
524 result [i] = generic_params [i];
529 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
531 generic_params = new GenericTypeParameterBuilder [names.Length];
532 for (int i = 0; i < names.Length; i++)
533 generic_params [i] = new GenericTypeParameterBuilder (
534 type, this, names [i], i);
536 return generic_params;
539 public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
543 this.attrs = attributes;
544 this.call_conv = callingConvention;
545 if ((attributes & MethodAttributes.Static) == 0)
546 this.call_conv |= CallingConventions.HasThis;
548 this.rtype = return_type;
549 this.parameters = new Type [parameter_types.Length];
550 System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
553 public void SetReturnType (Type returnType)
558 public void SetParameters (params Type[] parameterTypes)
560 if (parameterTypes != null) {
561 for (int i = 0; i < parameterTypes.Length; ++i)
562 if (parameterTypes [i] == null)
563 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
565 this.parameters = new Type [parameterTypes.Length];
566 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
570 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
571 SetReturnType (returnType);
572 SetParameters (parameterTypes);
573 this.returnModReq = returnTypeRequiredCustomModifiers;
574 this.returnModOpt = returnTypeOptionalCustomModifiers;
575 this.paramModReq = parameterTypeRequiredCustomModifiers;
576 this.paramModOpt = parameterTypeOptionalCustomModifiers;
579 public override Module Module {
586 void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
588 throw new NotImplementedException ();
591 void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
593 throw new NotImplementedException ();
596 void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
598 throw new NotImplementedException ();
601 void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
603 throw new NotImplementedException ();