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.
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Globalization;
38 using System.Security;
39 using System.Security.Permissions;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Diagnostics.SymbolStore;
44 namespace System.Reflection.Emit
47 [ComDefaultInterface (typeof (_MethodBuilder))]
48 [ClassInterface (ClassInterfaceType.None)]
49 [StructLayout (LayoutKind.Sequential)]
50 public sealed class MethodBuilder : MethodInfo, _MethodBuilder
52 #pragma warning disable 169, 414
53 private RuntimeMethodHandle mhandle;
55 internal Type[] parameters;
56 private MethodAttributes attrs; /* It's used directly by MCS */
57 private MethodImplAttributes iattrs;
59 private int table_idx;
61 private ILGenerator ilgen;
62 private TypeBuilder type;
63 internal ParameterBuilder[] pinfo;
64 private CustomAttributeBuilder[] cattrs;
65 private MethodInfo[] override_methods;
66 private string pi_dll;
67 private string pi_entry;
68 private CharSet charset;
69 private uint extra_flags; /* this encodes set_last_error etc */
70 private CallingConvention native_cc;
71 private CallingConventions call_conv;
72 private bool init_locals = true;
73 private IntPtr generic_container;
74 internal GenericTypeParameterBuilder[] generic_params;
75 private Type[] returnModReq;
76 private Type[] returnModOpt;
77 private Type[][] paramModReq;
78 private Type[][] paramModOpt;
79 private RefEmitPermissionSet[] permissions;
80 #pragma warning restore 169, 414
82 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt)
85 this.attrs = attributes;
86 this.call_conv = callingConvention;
87 this.rtype = returnType;
88 this.returnModReq = returnModReq;
89 this.returnModOpt = returnModOpt;
90 this.paramModReq = paramModReq;
91 this.paramModOpt = paramModOpt;
92 // The MSDN docs does not specify this, but the MS MethodBuilder
93 // appends a HasThis flag if the method is not static
94 if ((attributes & MethodAttributes.Static) == 0)
95 this.call_conv |= CallingConventions.HasThis;
96 if (parameterTypes != null) {
97 for (int i = 0; i < parameterTypes.Length; ++i)
98 if (parameterTypes [i] == null)
99 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
101 this.parameters = new Type [parameterTypes.Length];
102 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
105 table_idx = get_next_table_index (this, 0x06, true);
107 ((ModuleBuilder)tb.Module).RegisterToken (this, GetToken ().Token);
110 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes,
111 CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt,
112 String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset)
113 : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt)
116 pi_entry = entryName;
117 native_cc = nativeCConv;
118 charset = nativeCharset;
121 public override bool ContainsGenericParameters {
122 get { throw new NotSupportedException (); }
125 public bool InitLocals {
126 get {return init_locals;}
127 set {init_locals = value;}
130 internal TypeBuilder TypeBuilder {
134 public override RuntimeMethodHandle MethodHandle {
136 throw NotSupported ();
140 public override Type ReturnType {
141 get { return rtype; }
144 public override Type ReflectedType {
148 public override Type DeclaringType {
152 public override string Name {
156 public override MethodAttributes Attributes {
157 get { return attrs; }
160 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
164 public override CallingConventions CallingConvention {
165 get { return call_conv; }
168 [MonoTODO("Not implemented")]
169 public string Signature {
171 throw new NotImplementedException ();
176 internal bool BestFitMapping {
178 extra_flags = (uint) ((extra_flags & ~0x30) | (uint)(value ? 0x10 : 0x20));
183 internal bool ThrowOnUnmappableChar {
185 extra_flags = (uint) ((extra_flags & ~0x3000) | (uint)(value ? 0x1000 : 0x2000));
190 internal bool ExactSpelling {
192 extra_flags = (uint) ((extra_flags & ~0x01) | (uint)(value ? 0x01 : 0x00));
197 internal bool SetLastError {
199 extra_flags = (uint) ((extra_flags & ~0x40) | (uint)(value ? 0x40 : 0x00));
203 public MethodToken GetToken()
205 return new MethodToken(0x06000000 | table_idx);
208 public override MethodInfo GetBaseDefinition()
213 public override MethodImplAttributes GetMethodImplementationFlags()
218 public override ParameterInfo[] GetParameters()
220 if (!type.is_created)
221 throw NotSupported ();
222 if (parameters == null)
225 ParameterInfo[] retval = new ParameterInfo [parameters.Length];
226 for (int i = 0; i < parameters.Length; i++) {
227 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
232 internal override int GetParameterCount ()
234 if (parameters == null)
237 return parameters.Length;
240 internal override Type GetParameterType (int pos) {
241 return parameters [pos];
244 public Module GetModule ()
249 public void CreateMethodBody (byte[] il, int count)
251 if ((il != null) && ((count < 0) || (count > il.Length)))
252 throw new ArgumentOutOfRangeException ("Index was out of range. Must be non-negative and less than the size of the collection.");
254 if ((code != null) || type.is_created)
255 throw new InvalidOperationException ("Type definition of the method is complete.");
260 code = new byte [count];
261 System.Array.Copy(il, code, count);
265 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
267 throw NotSupported ();
270 public override bool IsDefined (Type attributeType, bool inherit)
272 throw NotSupported ();
275 public override object[] GetCustomAttributes (bool inherit)
278 * On MS.NET, this always returns not_supported, but we can't do this
279 * since there would be no way to obtain custom attributes of
280 * dynamically created ctors.
283 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
285 throw NotSupported ();
288 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
291 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
293 throw NotSupported ();
296 public ILGenerator GetILGenerator ()
298 return GetILGenerator (64);
301 public ILGenerator GetILGenerator (int size)
303 if (((iattrs & MethodImplAttributes.CodeTypeMask) !=
304 MethodImplAttributes.IL) ||
305 ((iattrs & MethodImplAttributes.ManagedMask) !=
306 MethodImplAttributes.Managed))
307 throw new InvalidOperationException ("Method body should not exist.");
310 ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
314 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
319 // Extension: Mono allows position == 0 for the return attribute
321 if ((position < 0) || (position > parameters.Length))
322 throw new ArgumentOutOfRangeException ("position");
324 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
326 pinfo = new ParameterBuilder [parameters.Length + 1];
327 pinfo [position] = pb;
331 internal void check_override ()
333 if (override_methods != null) {
334 foreach (var m in override_methods) {
335 if (m.IsVirtual && !IsVirtual)
336 throw new TypeLoadException (String.Format("Method '{0}' override '{1}' but it is not virtual", name, m));
341 internal void fixup ()
343 if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
344 // do not allow zero length method body on MS.NET 2.0 (and higher)
345 if (((ilgen == null) || (ilgen.ILOffset == 0)) && (code == null || code.Length == 0))
346 throw new InvalidOperationException (
347 String.Format ("Method '{0}.{1}' does not have a method body.",
348 DeclaringType.FullName, Name));
351 ilgen.label_fixup ();
354 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
356 if (ilgen != null && ilgen.HasDebugInfo) {
357 SymbolToken token = new SymbolToken (GetToken().Token);
358 symbolWriter.OpenMethod (token);
359 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
360 ilgen.GenerateDebugInfo (symbolWriter);
361 symbolWriter.CloseMethod ();
365 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
367 if (customBuilder == null)
368 throw new ArgumentNullException ("customBuilder");
370 switch (customBuilder.Ctor.ReflectedType.FullName) {
371 case "System.Runtime.CompilerServices.MethodImplAttribute":
372 byte[] data = customBuilder.Data;
373 int impla; // the (stupid) ctor takes a short or an int ...
374 impla = (int)data [2];
375 impla |= ((int)data [3]) << 8;
376 iattrs |= (MethodImplAttributes)impla;
379 case "System.Runtime.InteropServices.DllImportAttribute":
380 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
381 bool preserveSig = true;
384 * It would be easier to construct a DllImportAttribute from
385 * the custom attribute builder, but the DllImportAttribute
386 * does not contain all the information required here, ie.
387 * - some parameters, like BestFitMapping has three values
388 * ("on", "off", "missing"), but DllImportAttribute only
389 * contains two (on/off).
390 * - PreserveSig is true by default, while it is false by
391 * default in DllImportAttribute.
394 pi_dll = (string)attr.ctorArgs[0];
395 if (pi_dll == null || pi_dll.Length == 0)
396 throw new ArgumentException ("DllName cannot be empty");
398 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
400 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
401 string name = attr.namedParamNames [i];
402 object value = attr.namedParamValues [i];
404 if (name == "CallingConvention")
405 native_cc = (CallingConvention)value;
406 else if (name == "CharSet")
407 charset = (CharSet)value;
408 else if (name == "EntryPoint")
409 pi_entry = (string)value;
410 else if (name == "ExactSpelling")
411 ExactSpelling = (bool)value;
412 else if (name == "SetLastError")
413 SetLastError = (bool)value;
414 else if (name == "PreserveSig")
415 preserveSig = (bool)value;
416 else if (name == "BestFitMapping")
417 BestFitMapping = (bool)value;
418 else if (name == "ThrowOnUnmappableChar")
419 ThrowOnUnmappableChar = (bool)value;
422 attrs |= MethodAttributes.PinvokeImpl;
424 iattrs |= MethodImplAttributes.PreserveSig;
427 case "System.Runtime.InteropServices.PreserveSigAttribute":
428 iattrs |= MethodImplAttributes.PreserveSig;
430 case "System.Runtime.CompilerServices.SpecialNameAttribute":
431 attrs |= MethodAttributes.SpecialName;
433 case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
434 attrs |= MethodAttributes.HasSecurity;
438 if (cattrs != null) {
439 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
440 cattrs.CopyTo (new_array, 0);
441 new_array [cattrs.Length] = customBuilder;
444 cattrs = new CustomAttributeBuilder [1];
445 cattrs [0] = customBuilder;
450 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
453 throw new ArgumentNullException ("con");
454 if (binaryAttribute == null)
455 throw new ArgumentNullException ("binaryAttribute");
456 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
459 public void SetImplementationFlags (MethodImplAttributes attributes)
465 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
469 throw new ArgumentNullException ("pset");
470 if ((action == SecurityAction.RequestMinimum) ||
471 (action == SecurityAction.RequestOptional) ||
472 (action == SecurityAction.RequestRefuse))
473 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
477 if (permissions != null) {
478 /* Check duplicate actions */
479 foreach (RefEmitPermissionSet set in permissions)
480 if (set.action == action)
481 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
483 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
484 permissions.CopyTo (new_array, 0);
485 permissions = new_array;
488 permissions = new RefEmitPermissionSet [1];
490 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
491 attrs |= MethodAttributes.HasSecurity;
495 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
496 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
499 throw new NotImplementedException ();
503 public void SetSymCustomAttribute (string name, byte[] data)
506 throw new NotImplementedException ();
509 public override string ToString()
511 return "MethodBuilder [" + type.Name + "::" + name + "]";
515 public override bool Equals (object obj)
517 return base.Equals (obj);
520 public override int GetHashCode ()
522 return name.GetHashCode ();
525 internal override int get_next_table_index (object obj, int table, bool inc)
527 return type.get_next_table_index (obj, table, inc);
530 void ExtendArray<T> (ref T[] array, T elem) {
534 var newa = new T [array.Length + 1];
535 Array.Copy (array, newa, array.Length);
538 array [array.Length - 1] = elem;
541 internal void set_override (MethodInfo mdecl)
543 ExtendArray<MethodInfo> (ref override_methods, mdecl);
546 private void RejectIfCreated ()
549 throw new InvalidOperationException ("Type definition of the method is complete.");
552 private Exception NotSupported ()
554 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
557 public override MethodInfo MakeGenericMethod (params Type [] typeArguments)
559 if (!IsGenericMethodDefinition)
560 throw new InvalidOperationException ("Method is not a generic method definition");
561 if (typeArguments == null)
562 throw new ArgumentNullException ("typeArguments");
563 if (generic_params.Length != typeArguments.Length)
564 throw new ArgumentException ("Incorrect length", "typeArguments");
565 foreach (Type type in typeArguments) {
567 throw new ArgumentNullException ("typeArguments");
570 return new MethodOnTypeBuilderInst (this, typeArguments);
573 public override bool IsGenericMethodDefinition {
575 return generic_params != null;
579 public override bool IsGenericMethod {
581 return generic_params != null;
585 public override MethodInfo GetGenericMethodDefinition ()
587 if (!IsGenericMethodDefinition)
588 throw new InvalidOperationException ();
593 public override Type[] GetGenericArguments ()
595 if (generic_params == null)
598 Type[] result = new Type [generic_params.Length];
599 for (int i = 0; i < generic_params.Length; i++)
600 result [i] = generic_params [i];
605 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
608 throw new ArgumentNullException ("names");
609 if (names.Length == 0)
610 throw new ArgumentException ("names");
612 generic_params = new GenericTypeParameterBuilder [names.Length];
613 for (int i = 0; i < names.Length; i++) {
614 string item = names [i];
616 throw new ArgumentNullException ("names");
617 generic_params [i] = new GenericTypeParameterBuilder (type, this, item, i);
620 return generic_params;
623 public void SetReturnType (Type returnType)
628 public void SetParameters (params Type[] parameterTypes)
630 if (parameterTypes != null) {
631 for (int i = 0; i < parameterTypes.Length; ++i)
632 if (parameterTypes [i] == null)
633 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
635 this.parameters = new Type [parameterTypes.Length];
636 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
640 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
642 SetReturnType (returnType);
643 SetParameters (parameterTypes);
644 this.returnModReq = returnTypeRequiredCustomModifiers;
645 this.returnModOpt = returnTypeOptionalCustomModifiers;
646 this.paramModReq = parameterTypeRequiredCustomModifiers;
647 this.paramModOpt = parameterTypeOptionalCustomModifiers;
650 public override Module Module {
656 void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
658 throw new NotImplementedException ();
661 void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
663 throw new NotImplementedException ();
666 void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
668 throw new NotImplementedException ();
671 void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
673 throw new NotImplementedException ();
676 #if NET_4_0 || MOONLIGHT
677 public override ParameterInfo ReturnParameter {
678 get { return base.ReturnParameter; }