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))]
47 [ClassInterface (ClassInterfaceType.None)]
48 [StructLayout (LayoutKind.Sequential)]
49 public sealed class MethodBuilder : MethodInfo, _MethodBuilder
51 #pragma warning disable 169, 414
52 private RuntimeMethodHandle mhandle;
54 internal Type[] parameters;
55 private MethodAttributes attrs; /* It's used directly by MCS */
56 private MethodImplAttributes iattrs;
58 private int table_idx;
60 private ILGenerator ilgen;
61 private TypeBuilder type;
62 internal ParameterBuilder[] pinfo;
63 private CustomAttributeBuilder[] cattrs;
64 private MethodInfo[] override_methods;
65 private string pi_dll;
66 private string pi_entry;
67 private CharSet charset;
68 private uint extra_flags; /* this encodes set_last_error etc */
69 private CallingConvention native_cc;
70 private CallingConventions call_conv;
71 private bool init_locals = true;
72 private IntPtr generic_container;
73 internal GenericTypeParameterBuilder[] generic_params;
74 private Type[] returnModReq;
75 private Type[] returnModOpt;
76 private Type[][] paramModReq;
77 private Type[][] paramModOpt;
78 private RefEmitPermissionSet[] permissions;
79 #pragma warning restore 169, 414
81 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);
106 ((ModuleBuilder)tb.Module).RegisterToken (this, GetToken ().Token);
109 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes,
110 CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt,
111 String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset)
112 : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt)
115 pi_entry = entryName;
116 native_cc = nativeCConv;
117 charset = nativeCharset;
120 public override bool ContainsGenericParameters {
121 get { throw new NotSupportedException (); }
124 public bool InitLocals {
125 get {return init_locals;}
126 set {init_locals = value;}
129 internal TypeBuilder TypeBuilder {
133 public override RuntimeMethodHandle MethodHandle {
135 throw NotSupported ();
139 public override Type ReturnType {
140 get { return rtype; }
143 public override Type ReflectedType {
147 public override Type DeclaringType {
151 public override string Name {
155 public override MethodAttributes Attributes {
156 get { return attrs; }
159 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
163 public override CallingConventions CallingConvention {
164 get { return call_conv; }
167 [MonoTODO("Not implemented")]
168 public string Signature {
170 throw new NotImplementedException ();
175 internal bool BestFitMapping {
177 extra_flags = (uint) ((extra_flags & ~0x30) | (uint)(value ? 0x10 : 0x20));
182 internal bool ThrowOnUnmappableChar {
184 extra_flags = (uint) ((extra_flags & ~0x3000) | (uint)(value ? 0x1000 : 0x2000));
189 internal bool ExactSpelling {
191 extra_flags = (uint) ((extra_flags & ~0x01) | (uint)(value ? 0x01 : 0x00));
196 internal bool SetLastError {
198 extra_flags = (uint) ((extra_flags & ~0x40) | (uint)(value ? 0x40 : 0x00));
202 public MethodToken GetToken()
204 return new MethodToken(0x06000000 | table_idx);
207 public override MethodInfo GetBaseDefinition()
212 public override MethodImplAttributes GetMethodImplementationFlags()
217 public override ParameterInfo[] GetParameters()
219 if (!type.is_created)
220 throw NotSupported ();
221 if (parameters == null)
224 ParameterInfo[] retval = new ParameterInfo [parameters.Length];
225 for (int i = 0; i < parameters.Length; i++) {
226 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
231 internal override int GetParameterCount ()
233 if (parameters == null)
236 return parameters.Length;
239 internal override Type GetParameterType (int pos) {
240 return parameters [pos];
243 public Module GetModule ()
248 public void CreateMethodBody (byte[] il, int count)
250 if ((il != null) && ((count < 0) || (count > il.Length)))
251 throw new ArgumentOutOfRangeException ("Index was out of range. Must be non-negative and less than the size of the collection.");
253 if ((code != null) || type.is_created)
254 throw new InvalidOperationException ("Type definition of the method is complete.");
259 code = new byte [count];
260 System.Array.Copy(il, code, count);
264 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
266 throw NotSupported ();
269 public override bool IsDefined (Type attributeType, bool inherit)
271 throw NotSupported ();
274 public override object[] GetCustomAttributes (bool inherit)
277 * On MS.NET, this always returns not_supported, but we can't do this
278 * since there would be no way to obtain custom attributes of
279 * dynamically created ctors.
282 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
284 throw NotSupported ();
287 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
290 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
292 throw NotSupported ();
295 public ILGenerator GetILGenerator ()
297 return GetILGenerator (64);
300 public ILGenerator GetILGenerator (int size)
302 if (((iattrs & MethodImplAttributes.CodeTypeMask) !=
303 MethodImplAttributes.IL) ||
304 ((iattrs & MethodImplAttributes.ManagedMask) !=
305 MethodImplAttributes.Managed))
306 throw new InvalidOperationException ("Method body should not exist.");
309 ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
313 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
318 // Extension: Mono allows position == 0 for the return attribute
320 if ((position < 0) || (position > parameters.Length))
321 throw new ArgumentOutOfRangeException ("position");
323 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
325 pinfo = new ParameterBuilder [parameters.Length + 1];
326 pinfo [position] = pb;
330 internal void check_override ()
332 if (override_methods != null) {
333 foreach (var m in override_methods) {
334 if (m.IsVirtual && !IsVirtual)
335 throw new TypeLoadException (String.Format("Method '{0}' override '{1}' but it is not virtual", name, m));
340 internal void fixup ()
342 if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
343 // do not allow zero length method body on MS.NET 2.0 (and higher)
344 if (((ilgen == null) || (ilgen.ILOffset == 0)) && (code == null || code.Length == 0))
345 throw new InvalidOperationException (
346 String.Format ("Method '{0}.{1}' does not have a method body.",
347 DeclaringType.FullName, Name));
350 ilgen.label_fixup ();
353 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
355 if (ilgen != null && ilgen.HasDebugInfo) {
356 SymbolToken token = new SymbolToken (GetToken().Token);
357 symbolWriter.OpenMethod (token);
358 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
359 ilgen.GenerateDebugInfo (symbolWriter);
360 symbolWriter.CloseMethod ();
364 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
366 if (customBuilder == null)
367 throw new ArgumentNullException ("customBuilder");
369 switch (customBuilder.Ctor.ReflectedType.FullName) {
370 case "System.Runtime.CompilerServices.MethodImplAttribute":
371 byte[] data = customBuilder.Data;
372 int impla; // the (stupid) ctor takes a short or an int ...
373 impla = (int)data [2];
374 impla |= ((int)data [3]) << 8;
375 iattrs |= (MethodImplAttributes)impla;
378 case "System.Runtime.InteropServices.DllImportAttribute":
379 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
380 bool preserveSig = true;
383 * It would be easier to construct a DllImportAttribute from
384 * the custom attribute builder, but the DllImportAttribute
385 * does not contain all the information required here, ie.
386 * - some parameters, like BestFitMapping has three values
387 * ("on", "off", "missing"), but DllImportAttribute only
388 * contains two (on/off).
389 * - PreserveSig is true by default, while it is false by
390 * default in DllImportAttribute.
393 pi_dll = (string)attr.ctorArgs[0];
394 if (pi_dll == null || pi_dll.Length == 0)
395 throw new ArgumentException ("DllName cannot be empty");
397 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
399 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
400 string name = attr.namedParamNames [i];
401 object value = attr.namedParamValues [i];
403 if (name == "CallingConvention")
404 native_cc = (CallingConvention)value;
405 else if (name == "CharSet")
406 charset = (CharSet)value;
407 else if (name == "EntryPoint")
408 pi_entry = (string)value;
409 else if (name == "ExactSpelling")
410 ExactSpelling = (bool)value;
411 else if (name == "SetLastError")
412 SetLastError = (bool)value;
413 else if (name == "PreserveSig")
414 preserveSig = (bool)value;
415 else if (name == "BestFitMapping")
416 BestFitMapping = (bool)value;
417 else if (name == "ThrowOnUnmappableChar")
418 ThrowOnUnmappableChar = (bool)value;
421 attrs |= MethodAttributes.PinvokeImpl;
423 iattrs |= MethodImplAttributes.PreserveSig;
426 case "System.Runtime.InteropServices.PreserveSigAttribute":
427 iattrs |= MethodImplAttributes.PreserveSig;
429 case "System.Runtime.CompilerServices.SpecialNameAttribute":
430 attrs |= MethodAttributes.SpecialName;
432 case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
433 attrs |= MethodAttributes.HasSecurity;
437 if (cattrs != null) {
438 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
439 cattrs.CopyTo (new_array, 0);
440 new_array [cattrs.Length] = customBuilder;
443 cattrs = new CustomAttributeBuilder [1];
444 cattrs [0] = customBuilder;
449 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
452 throw new ArgumentNullException ("con");
453 if (binaryAttribute == null)
454 throw new ArgumentNullException ("binaryAttribute");
455 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
458 public void SetImplementationFlags (MethodImplAttributes attributes)
464 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
468 throw new ArgumentNullException ("pset");
469 if ((action == SecurityAction.RequestMinimum) ||
470 (action == SecurityAction.RequestOptional) ||
471 (action == SecurityAction.RequestRefuse))
472 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
476 if (permissions != null) {
477 /* Check duplicate actions */
478 foreach (RefEmitPermissionSet set in permissions)
479 if (set.action == action)
480 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
482 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
483 permissions.CopyTo (new_array, 0);
484 permissions = new_array;
487 permissions = new RefEmitPermissionSet [1];
489 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
490 attrs |= MethodAttributes.HasSecurity;
494 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
495 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
498 throw new NotImplementedException ();
502 public void SetSymCustomAttribute (string name, byte[] data)
505 throw new NotImplementedException ();
508 public override string ToString()
510 return "MethodBuilder [" + type.Name + "::" + name + "]";
514 public override bool Equals (object obj)
516 return base.Equals (obj);
519 public override int GetHashCode ()
521 return name.GetHashCode ();
524 internal override int get_next_table_index (object obj, int table, bool inc)
526 return type.get_next_table_index (obj, table, inc);
529 void ExtendArray<T> (ref T[] array, T elem) {
533 var newa = new T [array.Length + 1];
534 Array.Copy (array, newa, array.Length);
537 array [array.Length - 1] = elem;
540 internal void set_override (MethodInfo mdecl)
542 ExtendArray<MethodInfo> (ref override_methods, mdecl);
545 private void RejectIfCreated ()
548 throw new InvalidOperationException ("Type definition of the method is complete.");
551 private Exception NotSupported ()
553 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
556 public override MethodInfo MakeGenericMethod (params Type [] typeArguments)
558 if (!IsGenericMethodDefinition)
559 throw new InvalidOperationException ("Method is not a generic method definition");
560 if (typeArguments == null)
561 throw new ArgumentNullException ("typeArguments");
562 if (generic_params.Length != typeArguments.Length)
563 throw new ArgumentException ("Incorrect length", "typeArguments");
564 foreach (Type type in typeArguments) {
566 throw new ArgumentNullException ("typeArguments");
569 return new MethodOnTypeBuilderInst (this, typeArguments);
572 public override bool IsGenericMethodDefinition {
574 return generic_params != null;
578 public override bool IsGenericMethod {
580 return generic_params != null;
584 public override MethodInfo GetGenericMethodDefinition ()
586 if (!IsGenericMethodDefinition)
587 throw new InvalidOperationException ();
592 public override Type[] GetGenericArguments ()
594 if (generic_params == null)
597 Type[] result = new Type [generic_params.Length];
598 for (int i = 0; i < generic_params.Length; i++)
599 result [i] = generic_params [i];
604 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
607 throw new ArgumentNullException ("names");
608 if (names.Length == 0)
609 throw new ArgumentException ("names");
611 generic_params = new GenericTypeParameterBuilder [names.Length];
612 for (int i = 0; i < names.Length; i++) {
613 string item = names [i];
615 throw new ArgumentNullException ("names");
616 generic_params [i] = new GenericTypeParameterBuilder (type, this, item, i);
619 return generic_params;
622 public void SetReturnType (Type returnType)
627 public void SetParameters (params Type[] parameterTypes)
629 if (parameterTypes != null) {
630 for (int i = 0; i < parameterTypes.Length; ++i)
631 if (parameterTypes [i] == null)
632 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
634 this.parameters = new Type [parameterTypes.Length];
635 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
639 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
641 SetReturnType (returnType);
642 SetParameters (parameterTypes);
643 this.returnModReq = returnTypeRequiredCustomModifiers;
644 this.returnModOpt = returnTypeOptionalCustomModifiers;
645 this.paramModReq = parameterTypeRequiredCustomModifiers;
646 this.paramModOpt = parameterTypeOptionalCustomModifiers;
649 public override Module Module {
655 void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
657 throw new NotImplementedException ();
660 void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
662 throw new NotImplementedException ();
665 void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
667 throw new NotImplementedException ();
670 void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
672 throw new NotImplementedException ();
675 #if NET_4_0 || MOONLIGHT
676 public override ParameterInfo ReturnParameter {
677 get { return base.ReturnParameter; }