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 ();
223 return GetParametersInternal ();
226 internal override ParameterInfo[] GetParametersInternal ()
228 if (parameters == null)
231 ParameterInfo[] retval = new ParameterInfo [parameters.Length];
232 for (int i = 0; i < parameters.Length; i++) {
233 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
238 internal override int GetParametersCount ()
240 if (parameters == null)
243 return parameters.Length;
246 internal override Type GetParameterType (int pos) {
247 return parameters [pos];
250 public Module GetModule ()
255 public void CreateMethodBody (byte[] il, int count)
257 if ((il != null) && ((count < 0) || (count > il.Length)))
258 throw new ArgumentOutOfRangeException ("Index was out of range. Must be non-negative and less than the size of the collection.");
260 if ((code != null) || type.is_created)
261 throw new InvalidOperationException ("Type definition of the method is complete.");
266 code = new byte [count];
267 System.Array.Copy(il, code, count);
271 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
273 throw NotSupported ();
276 public override bool IsDefined (Type attributeType, bool inherit)
278 throw NotSupported ();
281 public override object[] GetCustomAttributes (bool inherit)
284 * On MS.NET, this always returns not_supported, but we can't do this
285 * since there would be no way to obtain custom attributes of
286 * dynamically created ctors.
289 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
291 throw NotSupported ();
294 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
297 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
299 throw NotSupported ();
302 public ILGenerator GetILGenerator ()
304 return GetILGenerator (64);
307 public ILGenerator GetILGenerator (int size)
309 if (((iattrs & MethodImplAttributes.CodeTypeMask) !=
310 MethodImplAttributes.IL) ||
311 ((iattrs & MethodImplAttributes.ManagedMask) !=
312 MethodImplAttributes.Managed))
313 throw new InvalidOperationException ("Method body should not exist.");
316 ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
320 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
325 // Extension: Mono allows position == 0 for the return attribute
327 if ((position < 0) || (position > parameters.Length))
328 throw new ArgumentOutOfRangeException ("position");
330 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
332 pinfo = new ParameterBuilder [parameters.Length + 1];
333 pinfo [position] = pb;
337 internal void check_override ()
339 if (override_methods != null) {
340 foreach (var m in override_methods) {
341 if (m.IsVirtual && !IsVirtual)
342 throw new TypeLoadException (String.Format("Method '{0}' override '{1}' but it is not virtual", name, m));
347 internal void fixup ()
349 if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
350 // do not allow zero length method body on MS.NET 2.0 (and higher)
351 if (((ilgen == null) || (ilgen.ILOffset == 0)) && (code == null || code.Length == 0))
352 throw new InvalidOperationException (
353 String.Format ("Method '{0}.{1}' does not have a method body.",
354 DeclaringType.FullName, Name));
357 ilgen.label_fixup (this);
360 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
362 if (ilgen != null && ilgen.HasDebugInfo) {
363 SymbolToken token = new SymbolToken (GetToken().Token);
364 symbolWriter.OpenMethod (token);
365 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
366 ilgen.GenerateDebugInfo (symbolWriter);
367 symbolWriter.CloseMethod ();
371 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
373 if (customBuilder == null)
374 throw new ArgumentNullException ("customBuilder");
376 switch (customBuilder.Ctor.ReflectedType.FullName) {
377 case "System.Runtime.CompilerServices.MethodImplAttribute":
378 byte[] data = customBuilder.Data;
379 int impla; // the (stupid) ctor takes a short or an int ...
380 impla = (int)data [2];
381 impla |= ((int)data [3]) << 8;
382 iattrs |= (MethodImplAttributes)impla;
385 case "System.Runtime.InteropServices.DllImportAttribute":
386 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
387 bool preserveSig = true;
390 * It would be easier to construct a DllImportAttribute from
391 * the custom attribute builder, but the DllImportAttribute
392 * does not contain all the information required here, ie.
393 * - some parameters, like BestFitMapping has three values
394 * ("on", "off", "missing"), but DllImportAttribute only
395 * contains two (on/off).
396 * - PreserveSig is true by default, while it is false by
397 * default in DllImportAttribute.
400 pi_dll = (string)attr.ctorArgs[0];
401 if (pi_dll == null || pi_dll.Length == 0)
402 throw new ArgumentException ("DllName cannot be empty");
404 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
406 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
407 string name = attr.namedParamNames [i];
408 object value = attr.namedParamValues [i];
410 if (name == "CallingConvention")
411 native_cc = (CallingConvention)value;
412 else if (name == "CharSet")
413 charset = (CharSet)value;
414 else if (name == "EntryPoint")
415 pi_entry = (string)value;
416 else if (name == "ExactSpelling")
417 ExactSpelling = (bool)value;
418 else if (name == "SetLastError")
419 SetLastError = (bool)value;
420 else if (name == "PreserveSig")
421 preserveSig = (bool)value;
422 else if (name == "BestFitMapping")
423 BestFitMapping = (bool)value;
424 else if (name == "ThrowOnUnmappableChar")
425 ThrowOnUnmappableChar = (bool)value;
428 attrs |= MethodAttributes.PinvokeImpl;
430 iattrs |= MethodImplAttributes.PreserveSig;
433 case "System.Runtime.InteropServices.PreserveSigAttribute":
434 iattrs |= MethodImplAttributes.PreserveSig;
436 case "System.Runtime.CompilerServices.SpecialNameAttribute":
437 attrs |= MethodAttributes.SpecialName;
439 case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
440 attrs |= MethodAttributes.HasSecurity;
444 if (cattrs != null) {
445 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
446 cattrs.CopyTo (new_array, 0);
447 new_array [cattrs.Length] = customBuilder;
450 cattrs = new CustomAttributeBuilder [1];
451 cattrs [0] = customBuilder;
456 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
459 throw new ArgumentNullException ("con");
460 if (binaryAttribute == null)
461 throw new ArgumentNullException ("binaryAttribute");
462 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
465 public void SetImplementationFlags (MethodImplAttributes attributes)
471 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
475 throw new ArgumentNullException ("pset");
476 if ((action == SecurityAction.RequestMinimum) ||
477 (action == SecurityAction.RequestOptional) ||
478 (action == SecurityAction.RequestRefuse))
479 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
483 if (permissions != null) {
484 /* Check duplicate actions */
485 foreach (RefEmitPermissionSet set in permissions)
486 if (set.action == action)
487 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
489 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
490 permissions.CopyTo (new_array, 0);
491 permissions = new_array;
494 permissions = new RefEmitPermissionSet [1];
496 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
497 attrs |= MethodAttributes.HasSecurity;
501 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
502 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
505 throw new NotImplementedException ();
509 public void SetSymCustomAttribute (string name, byte[] data)
512 throw new NotImplementedException ();
515 public override string ToString()
517 return "MethodBuilder [" + type.Name + "::" + name + "]";
521 public override bool Equals (object obj)
523 return base.Equals (obj);
526 public override int GetHashCode ()
528 return name.GetHashCode ();
531 internal override int get_next_table_index (object obj, int table, bool inc)
533 return type.get_next_table_index (obj, table, inc);
536 void ExtendArray<T> (ref T[] array, T elem) {
540 var newa = new T [array.Length + 1];
541 Array.Copy (array, newa, array.Length);
544 array [array.Length - 1] = elem;
547 internal void set_override (MethodInfo mdecl)
549 ExtendArray<MethodInfo> (ref override_methods, mdecl);
552 private void RejectIfCreated ()
555 throw new InvalidOperationException ("Type definition of the method is complete.");
558 private Exception NotSupported ()
560 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
563 public override MethodInfo MakeGenericMethod (params Type [] typeArguments)
565 if (!IsGenericMethodDefinition)
566 throw new InvalidOperationException ("Method is not a generic method definition");
567 if (typeArguments == null)
568 throw new ArgumentNullException ("typeArguments");
569 if (generic_params.Length != typeArguments.Length)
570 throw new ArgumentException ("Incorrect length", "typeArguments");
571 foreach (Type type in typeArguments) {
573 throw new ArgumentNullException ("typeArguments");
576 return new MethodOnTypeBuilderInst (this, typeArguments);
579 public override bool IsGenericMethodDefinition {
581 return generic_params != null;
585 public override bool IsGenericMethod {
587 return generic_params != null;
591 public override MethodInfo GetGenericMethodDefinition ()
593 if (!IsGenericMethodDefinition)
594 throw new InvalidOperationException ();
599 public override Type[] GetGenericArguments ()
601 if (generic_params == null)
604 Type[] result = new Type [generic_params.Length];
605 for (int i = 0; i < generic_params.Length; i++)
606 result [i] = generic_params [i];
611 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
614 throw new ArgumentNullException ("names");
615 if (names.Length == 0)
616 throw new ArgumentException ("names");
618 generic_params = new GenericTypeParameterBuilder [names.Length];
619 for (int i = 0; i < names.Length; i++) {
620 string item = names [i];
622 throw new ArgumentNullException ("names");
623 generic_params [i] = new GenericTypeParameterBuilder (type, this, item, i);
626 return generic_params;
629 public void SetReturnType (Type returnType)
634 public void SetParameters (params Type[] parameterTypes)
636 if (parameterTypes != null) {
637 for (int i = 0; i < parameterTypes.Length; ++i)
638 if (parameterTypes [i] == null)
639 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
641 this.parameters = new Type [parameterTypes.Length];
642 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
646 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
648 SetReturnType (returnType);
649 SetParameters (parameterTypes);
650 this.returnModReq = returnTypeRequiredCustomModifiers;
651 this.returnModOpt = returnTypeOptionalCustomModifiers;
652 this.paramModReq = parameterTypeRequiredCustomModifiers;
653 this.paramModOpt = parameterTypeOptionalCustomModifiers;
656 public override Module Module {
662 void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
664 throw new NotImplementedException ();
667 void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
669 throw new NotImplementedException ();
672 void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
674 throw new NotImplementedException ();
677 void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
679 throw new NotImplementedException ();
683 public override ParameterInfo ReturnParameter {
684 get { return base.ReturnParameter; }