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 public override Type ReturnType {
142 get { return rtype; }
145 public override Type ReflectedType {
149 public override Type DeclaringType {
153 public override string Name {
157 public override MethodAttributes Attributes {
158 get { return attrs; }
161 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
165 public override CallingConventions CallingConvention {
166 get { return call_conv; }
169 [MonoTODO("Not implemented")]
170 public string Signature {
172 throw new NotImplementedException ();
177 internal bool BestFitMapping {
179 extra_flags = (uint) ((extra_flags & ~0x30) | (uint)(value ? 0x10 : 0x20));
184 internal bool ThrowOnUnmappableChar {
186 extra_flags = (uint) ((extra_flags & ~0x3000) | (uint)(value ? 0x1000 : 0x2000));
191 internal bool ExactSpelling {
193 extra_flags = (uint) ((extra_flags & ~0x01) | (uint)(value ? 0x01 : 0x00));
198 internal bool SetLastError {
200 extra_flags = (uint) ((extra_flags & ~0x40) | (uint)(value ? 0x40 : 0x00));
204 public MethodToken GetToken()
206 return new MethodToken(0x06000000 | table_idx);
209 public override MethodInfo GetBaseDefinition()
214 public override MethodImplAttributes GetMethodImplementationFlags()
219 public override ParameterInfo[] GetParameters()
221 if (!type.is_created)
222 throw NotSupported ();
224 return GetParametersInternal ();
227 internal override ParameterInfo[] GetParametersInternal ()
229 if (parameters == null)
232 ParameterInfo[] retval = new ParameterInfo [parameters.Length];
233 for (int i = 0; i < parameters.Length; i++) {
234 retval [i] = ParameterInfo.New (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
239 internal override int GetParametersCount ()
241 if (parameters == null)
244 return parameters.Length;
247 internal override Type GetParameterType (int pos) {
248 return parameters [pos];
251 public Module GetModule ()
256 public void CreateMethodBody (byte[] il, int count)
258 if ((il != null) && ((count < 0) || (count > il.Length)))
259 throw new ArgumentOutOfRangeException ("Index was out of range. Must be non-negative and less than the size of the collection.");
261 if ((code != null) || type.is_created)
262 throw new InvalidOperationException ("Type definition of the method is complete.");
267 code = new byte [count];
268 System.Array.Copy(il, code, count);
272 public void SetMethodBody (byte[] il, int maxStack, byte[] localSignature,
273 IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
275 var ilgen = GetILGenerator ();
276 ilgen.Init (il, maxStack, localSignature, exceptionHandlers, tokenFixups);
279 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
281 throw NotSupported ();
284 public override bool IsDefined (Type attributeType, bool inherit)
286 throw NotSupported ();
289 public override object[] GetCustomAttributes (bool inherit)
292 * On MS.NET, this always returns not_supported, but we can't do this
293 * since there would be no way to obtain custom attributes of
294 * dynamically created ctors.
297 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
299 throw NotSupported ();
302 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
305 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
307 throw NotSupported ();
310 public ILGenerator GetILGenerator ()
312 return GetILGenerator (64);
315 public ILGenerator GetILGenerator (int size)
317 if (((iattrs & MethodImplAttributes.CodeTypeMask) !=
318 MethodImplAttributes.IL) ||
319 ((iattrs & MethodImplAttributes.ManagedMask) !=
320 MethodImplAttributes.Managed))
321 throw new InvalidOperationException ("Method body should not exist.");
324 ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
328 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
333 // Extension: Mono allows position == 0 for the return attribute
335 if ((position < 0) || (position > parameters.Length))
336 throw new ArgumentOutOfRangeException ("position");
338 ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
340 pinfo = new ParameterBuilder [parameters.Length + 1];
341 pinfo [position] = pb;
345 internal void check_override ()
347 if (override_methods != null) {
348 foreach (var m in override_methods) {
349 if (m.IsVirtual && !IsVirtual)
350 throw new TypeLoadException (String.Format("Method '{0}' override '{1}' but it is not virtual", name, m));
355 internal void fixup ()
357 if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
358 // do not allow zero length method body on MS.NET 2.0 (and higher)
359 if (((ilgen == null) || (ilgen.ILOffset == 0)) && (code == null || code.Length == 0))
360 throw new InvalidOperationException (
361 String.Format ("Method '{0}.{1}' does not have a method body.",
362 DeclaringType.FullName, Name));
365 ilgen.label_fixup (this);
368 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
370 if (ilgen != null && ilgen.HasDebugInfo) {
371 SymbolToken token = new SymbolToken (GetToken().Token);
372 symbolWriter.OpenMethod (token);
373 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
374 ilgen.GenerateDebugInfo (symbolWriter);
375 symbolWriter.CloseMethod ();
379 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
381 if (customBuilder == null)
382 throw new ArgumentNullException ("customBuilder");
384 switch (customBuilder.Ctor.ReflectedType.FullName) {
385 case "System.Runtime.CompilerServices.MethodImplAttribute":
386 byte[] data = customBuilder.Data;
387 int impla; // the (stupid) ctor takes a short or an int ...
388 impla = (int)data [2];
389 impla |= ((int)data [3]) << 8;
390 iattrs |= (MethodImplAttributes)impla;
393 case "System.Runtime.InteropServices.DllImportAttribute":
394 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
395 bool preserveSig = true;
398 * It would be easier to construct a DllImportAttribute from
399 * the custom attribute builder, but the DllImportAttribute
400 * does not contain all the information required here, ie.
401 * - some parameters, like BestFitMapping has three values
402 * ("on", "off", "missing"), but DllImportAttribute only
403 * contains two (on/off).
404 * - PreserveSig is true by default, while it is false by
405 * default in DllImportAttribute.
408 pi_dll = (string)attr.ctorArgs[0];
409 if (pi_dll == null || pi_dll.Length == 0)
410 throw new ArgumentException ("DllName cannot be empty");
412 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
414 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
415 string name = attr.namedParamNames [i];
416 object value = attr.namedParamValues [i];
418 if (name == "CallingConvention")
419 native_cc = (CallingConvention)value;
420 else if (name == "CharSet")
421 charset = (CharSet)value;
422 else if (name == "EntryPoint")
423 pi_entry = (string)value;
424 else if (name == "ExactSpelling")
425 ExactSpelling = (bool)value;
426 else if (name == "SetLastError")
427 SetLastError = (bool)value;
428 else if (name == "PreserveSig")
429 preserveSig = (bool)value;
430 else if (name == "BestFitMapping")
431 BestFitMapping = (bool)value;
432 else if (name == "ThrowOnUnmappableChar")
433 ThrowOnUnmappableChar = (bool)value;
436 attrs |= MethodAttributes.PinvokeImpl;
438 iattrs |= MethodImplAttributes.PreserveSig;
441 case "System.Runtime.InteropServices.PreserveSigAttribute":
442 iattrs |= MethodImplAttributes.PreserveSig;
444 case "System.Runtime.CompilerServices.SpecialNameAttribute":
445 attrs |= MethodAttributes.SpecialName;
447 case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
448 attrs |= MethodAttributes.HasSecurity;
452 if (cattrs != null) {
453 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
454 cattrs.CopyTo (new_array, 0);
455 new_array [cattrs.Length] = customBuilder;
458 cattrs = new CustomAttributeBuilder [1];
459 cattrs [0] = customBuilder;
464 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
467 throw new ArgumentNullException ("con");
468 if (binaryAttribute == null)
469 throw new ArgumentNullException ("binaryAttribute");
470 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
473 public void SetImplementationFlags (MethodImplAttributes attributes)
479 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
483 throw new ArgumentNullException ("pset");
484 if ((action == SecurityAction.RequestMinimum) ||
485 (action == SecurityAction.RequestOptional) ||
486 (action == SecurityAction.RequestRefuse))
487 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
491 if (permissions != null) {
492 /* Check duplicate actions */
493 foreach (RefEmitPermissionSet set in permissions)
494 if (set.action == action)
495 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
497 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
498 permissions.CopyTo (new_array, 0);
499 permissions = new_array;
502 permissions = new RefEmitPermissionSet [1];
504 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
505 attrs |= MethodAttributes.HasSecurity;
509 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
510 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
513 throw new NotImplementedException ();
517 public void SetSymCustomAttribute (string name, byte[] data)
520 throw new NotImplementedException ();
523 public override string ToString()
525 return "MethodBuilder [" + type.Name + "::" + name + "]";
529 public override bool Equals (object obj)
531 return base.Equals (obj);
534 public override int GetHashCode ()
536 return name.GetHashCode ();
539 internal override int get_next_table_index (object obj, int table, bool inc)
541 return type.get_next_table_index (obj, table, inc);
544 void ExtendArray<T> (ref T[] array, T elem) {
548 var newa = new T [array.Length + 1];
549 Array.Copy (array, newa, array.Length);
552 array [array.Length - 1] = elem;
555 internal void set_override (MethodInfo mdecl)
557 ExtendArray<MethodInfo> (ref override_methods, mdecl);
560 private void RejectIfCreated ()
563 throw new InvalidOperationException ("Type definition of the method is complete.");
566 private Exception NotSupported ()
568 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
571 public override MethodInfo MakeGenericMethod (params Type [] typeArguments)
573 if (!IsGenericMethodDefinition)
574 throw new InvalidOperationException ("Method is not a generic method definition");
575 if (typeArguments == null)
576 throw new ArgumentNullException ("typeArguments");
577 if (generic_params.Length != typeArguments.Length)
578 throw new ArgumentException ("Incorrect length", "typeArguments");
579 foreach (Type type in typeArguments) {
581 throw new ArgumentNullException ("typeArguments");
584 return new MethodOnTypeBuilderInst (this, typeArguments);
587 public override bool IsGenericMethodDefinition {
589 return generic_params != null;
593 public override bool IsGenericMethod {
595 return generic_params != null;
599 public override MethodInfo GetGenericMethodDefinition ()
601 if (!IsGenericMethodDefinition)
602 throw new InvalidOperationException ();
607 public override Type[] GetGenericArguments ()
609 if (generic_params == null)
612 Type[] result = new Type [generic_params.Length];
613 for (int i = 0; i < generic_params.Length; i++)
614 result [i] = generic_params [i];
619 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
622 throw new ArgumentNullException ("names");
623 if (names.Length == 0)
624 throw new ArgumentException ("names");
626 generic_params = new GenericTypeParameterBuilder [names.Length];
627 for (int i = 0; i < names.Length; i++) {
628 string item = names [i];
630 throw new ArgumentNullException ("names");
631 generic_params [i] = new GenericTypeParameterBuilder (type, this, item, i);
634 return generic_params;
637 public void SetReturnType (Type returnType)
642 public void SetParameters (params Type[] parameterTypes)
644 if (parameterTypes != null) {
645 for (int i = 0; i < parameterTypes.Length; ++i)
646 if (parameterTypes [i] == null)
647 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
649 this.parameters = new Type [parameterTypes.Length];
650 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
654 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
656 SetReturnType (returnType);
657 SetParameters (parameterTypes);
658 this.returnModReq = returnTypeRequiredCustomModifiers;
659 this.returnModOpt = returnTypeOptionalCustomModifiers;
660 this.paramModReq = parameterTypeRequiredCustomModifiers;
661 this.paramModOpt = parameterTypeOptionalCustomModifiers;
664 public override Module Module {
670 void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
672 throw new NotImplementedException ();
675 void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
677 throw new NotImplementedException ();
680 void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
682 throw new NotImplementedException ();
685 void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
687 throw new NotImplementedException ();
690 public override ParameterInfo ReturnParameter {
691 get { return base.ReturnParameter; }