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;
43 using System.Collections.Generic;
45 namespace System.Reflection.Emit
48 [ComDefaultInterface (typeof (_MethodBuilder))]
49 [ClassInterface (ClassInterfaceType.None)]
50 [StructLayout (LayoutKind.Sequential)]
51 public sealed class MethodBuilder : MethodInfo, _MethodBuilder
53 #pragma warning disable 169, 414
54 private RuntimeMethodHandle mhandle;
56 internal Type[] parameters;
57 private MethodAttributes attrs; /* It's used directly by MCS */
58 private MethodImplAttributes iattrs;
60 private int table_idx;
62 private ILGenerator ilgen;
63 private TypeBuilder type;
64 internal ParameterBuilder[] pinfo;
65 private CustomAttributeBuilder[] cattrs;
66 private MethodInfo[] override_methods;
67 private string pi_dll;
68 private string pi_entry;
69 private CharSet charset;
70 private uint extra_flags; /* this encodes set_last_error etc */
71 private CallingConvention native_cc;
72 private CallingConventions call_conv;
73 private bool init_locals = true;
74 private IntPtr generic_container;
75 internal GenericTypeParameterBuilder[] generic_params;
76 private Type[] returnModReq;
77 private Type[] returnModOpt;
78 private Type[][] paramModReq;
79 private Type[][] paramModOpt;
80 private RefEmitPermissionSet[] permissions;
81 #pragma warning restore 169, 414
83 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt)
86 this.attrs = attributes;
87 this.call_conv = callingConvention;
88 this.rtype = returnType;
89 this.returnModReq = returnModReq;
90 this.returnModOpt = returnModOpt;
91 this.paramModReq = paramModReq;
92 this.paramModOpt = paramModOpt;
93 // The MSDN docs does not specify this, but the MS MethodBuilder
94 // appends a HasThis flag if the method is not static
95 if ((attributes & MethodAttributes.Static) == 0)
96 this.call_conv |= CallingConventions.HasThis;
97 if (parameterTypes != null) {
98 for (int i = 0; i < parameterTypes.Length; ++i)
99 if (parameterTypes [i] == null)
100 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
102 this.parameters = new Type [parameterTypes.Length];
103 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
106 table_idx = get_next_table_index (this, 0x06, true);
108 ((ModuleBuilder)tb.Module).RegisterToken (this, GetToken ().Token);
111 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes,
112 CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt,
113 String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset)
114 : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt)
117 pi_entry = entryName;
118 native_cc = nativeCConv;
119 charset = nativeCharset;
122 public override bool ContainsGenericParameters {
123 get { throw new NotSupportedException (); }
126 public bool InitLocals {
127 get {return init_locals;}
128 set {init_locals = value;}
131 internal TypeBuilder TypeBuilder {
135 public override RuntimeMethodHandle MethodHandle {
137 throw NotSupported ();
141 internal RuntimeMethodHandle MethodHandleInternal {
147 public override Type ReturnType {
148 get { return rtype; }
151 public override Type ReflectedType {
155 public override Type DeclaringType {
159 public override string Name {
163 public override MethodAttributes Attributes {
164 get { return attrs; }
167 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
171 public override CallingConventions CallingConvention {
172 get { return call_conv; }
175 [MonoTODO("Not implemented")]
176 public string Signature {
178 throw new NotImplementedException ();
183 internal bool BestFitMapping {
185 extra_flags = (uint) ((extra_flags & ~0x30) | (uint)(value ? 0x10 : 0x20));
190 internal bool ThrowOnUnmappableChar {
192 extra_flags = (uint) ((extra_flags & ~0x3000) | (uint)(value ? 0x1000 : 0x2000));
197 internal bool ExactSpelling {
199 extra_flags = (uint) ((extra_flags & ~0x01) | (uint)(value ? 0x01 : 0x00));
204 internal bool SetLastError {
206 extra_flags = (uint) ((extra_flags & ~0x40) | (uint)(value ? 0x40 : 0x00));
210 public MethodToken GetToken()
212 return new MethodToken(0x06000000 | table_idx);
215 public override MethodInfo GetBaseDefinition()
220 public override MethodImplAttributes GetMethodImplementationFlags()
225 public override ParameterInfo[] GetParameters()
227 if (!type.is_created)
228 throw NotSupported ();
230 return GetParametersInternal ();
233 internal override ParameterInfo[] GetParametersInternal ()
235 if (parameters == null)
238 ParameterInfo[] retval = new ParameterInfo [parameters.Length];
239 for (int i = 0; i < parameters.Length; i++) {
240 retval [i] = ParameterInfo.New (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
245 internal override int GetParametersCount ()
247 if (parameters == null)
250 return parameters.Length;
253 internal override Type GetParameterType (int pos) {
254 return parameters [pos];
257 internal MethodBase RuntimeResolve () {
258 return type.RuntimeResolve ().GetMethod (this);
261 public Module GetModule ()
266 public void CreateMethodBody (byte[] il, int count)
268 if ((il != null) && ((count < 0) || (count > il.Length)))
269 throw new ArgumentOutOfRangeException ("Index was out of range. Must be non-negative and less than the size of the collection.");
271 if ((code != null) || type.is_created)
272 throw new InvalidOperationException ("Type definition of the method is complete.");
277 code = new byte [count];
278 System.Array.Copy(il, code, count);
282 public void SetMethodBody (byte[] il, int maxStack, byte[] localSignature,
283 IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
285 var ilgen = GetILGenerator ();
286 ilgen.Init (il, maxStack, localSignature, exceptionHandlers, tokenFixups);
289 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
291 throw NotSupported ();
294 public override bool IsDefined (Type attributeType, bool inherit)
296 throw NotSupported ();
299 public override object[] GetCustomAttributes (bool inherit)
302 * On MS.NET, this always returns not_supported, but we can't do this
303 * since there would be no way to obtain custom attributes of
304 * dynamically created ctors.
307 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
309 throw NotSupported ();
312 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
315 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
317 throw NotSupported ();
320 public ILGenerator GetILGenerator ()
322 return GetILGenerator (64);
325 public ILGenerator GetILGenerator (int size)
327 if (((iattrs & MethodImplAttributes.CodeTypeMask) !=
328 MethodImplAttributes.IL) ||
329 ((iattrs & MethodImplAttributes.ManagedMask) !=
330 MethodImplAttributes.Managed))
331 throw new InvalidOperationException ("Method body should not exist.");
334 ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
338 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
343 // Extension: Mono allows position == 0 for the return attribute
345 if ((position < 0) || (position > parameters.Length))
346 throw new ArgumentOutOfRangeException ("position");
348 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
350 pinfo = new ParameterBuilder [parameters.Length + 1];
351 pinfo [position] = pb;
355 internal void check_override ()
357 if (override_methods != null) {
358 foreach (var m in override_methods) {
359 if (m.IsVirtual && !IsVirtual)
360 throw new TypeLoadException (String.Format("Method '{0}' override '{1}' but it is not virtual", name, m));
365 internal void fixup ()
367 if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
368 // do not allow zero length method body on MS.NET 2.0 (and higher)
369 if (((ilgen == null) || (ilgen.ILOffset == 0)) && (code == null || code.Length == 0))
370 throw new InvalidOperationException (
371 String.Format ("Method '{0}.{1}' does not have a method body.",
372 DeclaringType.FullName, Name));
375 ilgen.label_fixup (this);
378 internal void ResolveUserTypes () {
379 rtype = TypeBuilder.ResolveUserType (rtype);
380 TypeBuilder.ResolveUserTypes (parameters);
381 TypeBuilder.ResolveUserTypes (returnModReq);
382 TypeBuilder.ResolveUserTypes (returnModOpt);
383 if (paramModReq != null) {
384 foreach (var types in paramModReq)
385 TypeBuilder.ResolveUserTypes (types);
387 if (paramModOpt != null) {
388 foreach (var types in paramModOpt)
389 TypeBuilder.ResolveUserTypes (types);
393 internal void FixupTokens (Dictionary<int, int> token_map, Dictionary<int, MemberInfo> member_map) {
395 ilgen.FixupTokens (token_map, member_map);
398 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
400 if (ilgen != null && ilgen.HasDebugInfo) {
401 SymbolToken token = new SymbolToken (GetToken().Token);
402 symbolWriter.OpenMethod (token);
403 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
404 ilgen.GenerateDebugInfo (symbolWriter);
405 symbolWriter.CloseMethod ();
409 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
411 if (customBuilder == null)
412 throw new ArgumentNullException ("customBuilder");
414 switch (customBuilder.Ctor.ReflectedType.FullName) {
415 case "System.Runtime.CompilerServices.MethodImplAttribute":
416 byte[] data = customBuilder.Data;
417 int impla; // the (stupid) ctor takes a short or an int ...
418 impla = (int)data [2];
419 impla |= ((int)data [3]) << 8;
420 iattrs |= (MethodImplAttributes)impla;
423 case "System.Runtime.InteropServices.DllImportAttribute":
424 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
425 bool preserveSig = true;
428 * It would be easier to construct a DllImportAttribute from
429 * the custom attribute builder, but the DllImportAttribute
430 * does not contain all the information required here, ie.
431 * - some parameters, like BestFitMapping has three values
432 * ("on", "off", "missing"), but DllImportAttribute only
433 * contains two (on/off).
434 * - PreserveSig is true by default, while it is false by
435 * default in DllImportAttribute.
438 pi_dll = (string)attr.ctorArgs[0];
439 if (pi_dll == null || pi_dll.Length == 0)
440 throw new ArgumentException ("DllName cannot be empty");
442 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
444 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
445 string name = attr.namedParamNames [i];
446 object value = attr.namedParamValues [i];
448 if (name == "CallingConvention")
449 native_cc = (CallingConvention)value;
450 else if (name == "CharSet")
451 charset = (CharSet)value;
452 else if (name == "EntryPoint")
453 pi_entry = (string)value;
454 else if (name == "ExactSpelling")
455 ExactSpelling = (bool)value;
456 else if (name == "SetLastError")
457 SetLastError = (bool)value;
458 else if (name == "PreserveSig")
459 preserveSig = (bool)value;
460 else if (name == "BestFitMapping")
461 BestFitMapping = (bool)value;
462 else if (name == "ThrowOnUnmappableChar")
463 ThrowOnUnmappableChar = (bool)value;
466 attrs |= MethodAttributes.PinvokeImpl;
468 iattrs |= MethodImplAttributes.PreserveSig;
471 case "System.Runtime.InteropServices.PreserveSigAttribute":
472 iattrs |= MethodImplAttributes.PreserveSig;
474 case "System.Runtime.CompilerServices.SpecialNameAttribute":
475 attrs |= MethodAttributes.SpecialName;
477 case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
478 attrs |= MethodAttributes.HasSecurity;
482 if (cattrs != null) {
483 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
484 cattrs.CopyTo (new_array, 0);
485 new_array [cattrs.Length] = customBuilder;
488 cattrs = new CustomAttributeBuilder [1];
489 cattrs [0] = customBuilder;
494 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
497 throw new ArgumentNullException ("con");
498 if (binaryAttribute == null)
499 throw new ArgumentNullException ("binaryAttribute");
500 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
503 public void SetImplementationFlags (MethodImplAttributes attributes)
509 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
513 throw new ArgumentNullException ("pset");
514 if ((action == SecurityAction.RequestMinimum) ||
515 (action == SecurityAction.RequestOptional) ||
516 (action == SecurityAction.RequestRefuse))
517 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
521 if (permissions != null) {
522 /* Check duplicate actions */
523 foreach (RefEmitPermissionSet set in permissions)
524 if (set.action == action)
525 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
527 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
528 permissions.CopyTo (new_array, 0);
529 permissions = new_array;
532 permissions = new RefEmitPermissionSet [1];
534 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
535 attrs |= MethodAttributes.HasSecurity;
539 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
540 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
543 throw new NotImplementedException ();
547 public void SetSymCustomAttribute (string name, byte[] data)
550 throw new NotImplementedException ();
553 public override string ToString()
555 return "MethodBuilder [" + type.Name + "::" + name + "]";
559 public override bool Equals (object obj)
561 return base.Equals (obj);
564 public override int GetHashCode ()
566 return name.GetHashCode ();
569 internal override int get_next_table_index (object obj, int table, bool inc)
571 return type.get_next_table_index (obj, table, inc);
574 void ExtendArray<T> (ref T[] array, T elem) {
578 var newa = new T [array.Length + 1];
579 Array.Copy (array, newa, array.Length);
582 array [array.Length - 1] = elem;
585 internal void set_override (MethodInfo mdecl)
587 ExtendArray<MethodInfo> (ref override_methods, mdecl);
590 private void RejectIfCreated ()
593 throw new InvalidOperationException ("Type definition of the method is complete.");
596 private Exception NotSupported ()
598 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
601 public override MethodInfo MakeGenericMethod (params Type [] typeArguments)
603 if (!IsGenericMethodDefinition)
604 throw new InvalidOperationException ("Method is not a generic method definition");
605 if (typeArguments == null)
606 throw new ArgumentNullException ("typeArguments");
607 if (generic_params.Length != typeArguments.Length)
608 throw new ArgumentException ("Incorrect length", "typeArguments");
609 foreach (Type type in typeArguments) {
611 throw new ArgumentNullException ("typeArguments");
614 return new MethodOnTypeBuilderInst (this, typeArguments);
617 public override bool IsGenericMethodDefinition {
619 return generic_params != null;
623 public override bool IsGenericMethod {
625 return generic_params != null;
629 public override MethodInfo GetGenericMethodDefinition ()
631 if (!IsGenericMethodDefinition)
632 throw new InvalidOperationException ();
637 public override Type[] GetGenericArguments ()
639 if (generic_params == null)
642 Type[] result = new Type [generic_params.Length];
643 for (int i = 0; i < generic_params.Length; i++)
644 result [i] = generic_params [i];
649 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
652 throw new ArgumentNullException ("names");
653 if (names.Length == 0)
654 throw new ArgumentException ("names");
656 generic_params = new GenericTypeParameterBuilder [names.Length];
657 for (int i = 0; i < names.Length; i++) {
658 string item = names [i];
660 throw new ArgumentNullException ("names");
661 generic_params [i] = new GenericTypeParameterBuilder (type, this, item, i);
664 return generic_params;
667 public void SetReturnType (Type returnType)
672 public void SetParameters (params Type[] parameterTypes)
674 if (parameterTypes != null) {
675 for (int i = 0; i < parameterTypes.Length; ++i)
676 if (parameterTypes [i] == null)
677 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
679 this.parameters = new Type [parameterTypes.Length];
680 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
684 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
686 SetReturnType (returnType);
687 SetParameters (parameterTypes);
688 this.returnModReq = returnTypeRequiredCustomModifiers;
689 this.returnModOpt = returnTypeOptionalCustomModifiers;
690 this.paramModReq = parameterTypeRequiredCustomModifiers;
691 this.paramModOpt = parameterTypeOptionalCustomModifiers;
694 public override Module Module {
700 void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
702 throw new NotImplementedException ();
705 void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
707 throw new NotImplementedException ();
710 void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
712 throw new NotImplementedException ();
715 void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
717 throw new NotImplementedException ();
720 public override ParameterInfo ReturnParameter {
721 get { return base.ReturnParameter; }