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 (
298 String.Format ("Method '{0}.{1}' does not have a method body.",
299 DeclaringType.Name, Name));
302 ilgen.label_fixup ();
305 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
307 if (ilgen != null && ilgen.HasDebugInfo) {
308 SymbolToken token = new SymbolToken (GetToken().Token);
309 symbolWriter.OpenMethod (token);
310 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
311 ilgen.GenerateDebugInfo (symbolWriter);
312 symbolWriter.CloseMethod ();
316 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
317 if (customBuilder == null)
318 throw new ArgumentNullException ("customBuilder");
319 string attrname = customBuilder.Ctor.ReflectedType.FullName;
320 if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
321 byte[] data = customBuilder.Data;
322 int impla; // the (stupid) ctor takes a short or an int ...
323 impla = (int)data [2];
324 impla |= ((int)data [3]) << 8;
325 SetImplementationFlags ((MethodImplAttributes)impla);
328 if (attrname == "System.Runtime.InteropServices.DllImportAttribute") {
329 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
330 bool preserveSig = true;
333 * It would be easier to construct a DllImportAttribute from
334 * the custom attribute builder, but the DllImportAttribute
335 * does not contain all the information required here, ie.
336 * - some parameters, like BestFitMapping has three values
337 * ("on", "off", "missing"), but DllImportAttribute only
338 * contains two (on/off).
339 * - PreserveSig is true by default, while it is false by
340 * default in DllImportAttribute.
343 pi_dll = (string)attr.ctorArgs [0];
344 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
346 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
347 string name = attr.namedParamNames [i];
348 object value = attr.namedParamValues [i];
350 if (name == "CallingConvention")
351 native_cc = (CallingConvention)value;
352 else if (name == "CharSet")
353 charset = (CharSet)value;
354 else if (name == "EntryPoint")
355 pi_entry = (string)value;
356 else if (name == "ExactSpelling")
357 ExactSpelling = (bool)value;
358 else if (name == "SetLastError")
359 SetLastError = (bool)value;
360 else if (name == "PreserveSig")
361 preserveSig = (bool)value;
363 else if (name == "BestFitMapping")
364 BestFitMapping = (bool)value;
365 else if (name == "ThrowOnUnmappableChar")
366 ThrowOnUnmappableChar = (bool)value;
370 attrs |= MethodAttributes.PinvokeImpl;
372 iattrs |= MethodImplAttributes.PreserveSig;
377 if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
378 attrs |= MethodAttributes.SpecialName;
383 if (cattrs != null) {
384 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
385 cattrs.CopyTo (new_array, 0);
386 new_array [cattrs.Length] = customBuilder;
389 cattrs = new CustomAttributeBuilder [1];
390 cattrs [0] = customBuilder;
397 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
399 throw new ArgumentNullException ("con");
400 if (binaryAttribute == null)
401 throw new ArgumentNullException ("binaryAttribute");
402 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
404 public void SetImplementationFlags( MethodImplAttributes attributes) {
409 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
411 throw new ArgumentNullException ("pset");
412 if ((action == SecurityAction.RequestMinimum) ||
413 (action == SecurityAction.RequestOptional) ||
414 (action == SecurityAction.RequestRefuse))
415 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
419 if (permissions != null) {
420 /* Check duplicate actions */
421 foreach (RefEmitPermissionSet set in permissions)
422 if (set.action == action)
423 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
425 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
426 permissions.CopyTo (new_array, 0);
427 permissions = new_array;
430 permissions = new RefEmitPermissionSet [1];
432 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
433 attrs |= MethodAttributes.HasSecurity;
437 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
439 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
442 throw new NotImplementedException ();
446 public void SetSymCustomAttribute (string name, byte[] data)
449 throw new NotImplementedException ();
452 public override string ToString()
454 return "MethodBuilder [" + type.Name + "::" + name + "]";
458 public override bool Equals (object obj)
460 return base.Equals (obj);
463 public override int GetHashCode ()
465 return name.GetHashCode ();
468 internal override int get_next_table_index (object obj, int table, bool inc) {
469 return type.get_next_table_index (obj, table, inc);
472 internal void set_override (MethodInfo mdecl) {
473 override_method = mdecl;
476 private void RejectIfCreated () {
478 throw new InvalidOperationException ("Type definition of the method is complete.");
481 private Exception NotSupported () {
482 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
485 #if NET_2_0 || BOOTSTRAP_NET_2_0
486 [MethodImplAttribute(MethodImplOptions.InternalCall)]
487 public override extern MethodInfo MakeGenericMethod (Type [] types);
489 public override bool IsGenericMethodDefinition {
491 return generic_params != null;
495 public override bool IsGenericMethod {
497 return generic_params != null;
501 public override MethodInfo GetGenericMethodDefinition ()
503 if (!IsGenericMethodDefinition)
504 throw new InvalidOperationException ();
509 public override Type[] GetGenericArguments ()
511 if (generic_params == null)
514 Type[] result = new Type [generic_params.Length];
515 for (int i = 0; i < generic_params.Length; i++)
516 result [i] = generic_params [i];
521 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
523 generic_params = new GenericTypeParameterBuilder [names.Length];
524 for (int i = 0; i < names.Length; i++)
525 generic_params [i] = new GenericTypeParameterBuilder (
526 type, this, names [i], i);
528 return generic_params;
531 public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
535 this.attrs = attributes;
536 this.call_conv = callingConvention;
537 if ((attributes & MethodAttributes.Static) == 0)
538 this.call_conv |= CallingConventions.HasThis;
540 this.rtype = return_type;
541 this.parameters = new Type [parameter_types.Length];
542 System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
545 public void SetReturnType (Type returnType)
550 public void SetParameters (params Type[] parameterTypes)
552 if (parameterTypes != null) {
553 for (int i = 0; i < parameterTypes.Length; ++i)
554 if (parameterTypes [i] == null)
555 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
557 this.parameters = new Type [parameterTypes.Length];
558 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
562 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
563 SetReturnType (returnType);
564 SetParameters (parameterTypes);
565 this.returnModReq = returnTypeRequiredCustomModifiers;
566 this.returnModOpt = returnTypeOptionalCustomModifiers;
567 this.paramModReq = parameterTypeRequiredCustomModifiers;
568 this.paramModOpt = parameterTypeOptionalCustomModifiers;
571 public override Module Module {
578 void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
580 throw new NotImplementedException ();
583 void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
585 throw new NotImplementedException ();
588 void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
590 throw new NotImplementedException ();
593 void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
595 throw new NotImplementedException ();