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 ResolveUserTypes () {
369 rtype = TypeBuilder.ResolveUserType (rtype);
370 TypeBuilder.ResolveUserTypes (parameters);
371 TypeBuilder.ResolveUserTypes (returnModReq);
372 TypeBuilder.ResolveUserTypes (returnModOpt);
373 if (paramModReq != null) {
374 foreach (var types in paramModReq)
375 TypeBuilder.ResolveUserTypes (types);
377 if (paramModOpt != null) {
378 foreach (var types in paramModOpt)
379 TypeBuilder.ResolveUserTypes (types);
383 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
385 if (ilgen != null && ilgen.HasDebugInfo) {
386 SymbolToken token = new SymbolToken (GetToken().Token);
387 symbolWriter.OpenMethod (token);
388 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
389 ilgen.GenerateDebugInfo (symbolWriter);
390 symbolWriter.CloseMethod ();
394 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
396 if (customBuilder == null)
397 throw new ArgumentNullException ("customBuilder");
399 switch (customBuilder.Ctor.ReflectedType.FullName) {
400 case "System.Runtime.CompilerServices.MethodImplAttribute":
401 byte[] data = customBuilder.Data;
402 int impla; // the (stupid) ctor takes a short or an int ...
403 impla = (int)data [2];
404 impla |= ((int)data [3]) << 8;
405 iattrs |= (MethodImplAttributes)impla;
408 case "System.Runtime.InteropServices.DllImportAttribute":
409 CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
410 bool preserveSig = true;
413 * It would be easier to construct a DllImportAttribute from
414 * the custom attribute builder, but the DllImportAttribute
415 * does not contain all the information required here, ie.
416 * - some parameters, like BestFitMapping has three values
417 * ("on", "off", "missing"), but DllImportAttribute only
418 * contains two (on/off).
419 * - PreserveSig is true by default, while it is false by
420 * default in DllImportAttribute.
423 pi_dll = (string)attr.ctorArgs[0];
424 if (pi_dll == null || pi_dll.Length == 0)
425 throw new ArgumentException ("DllName cannot be empty");
427 native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
429 for (int i = 0; i < attr.namedParamNames.Length; ++i) {
430 string name = attr.namedParamNames [i];
431 object value = attr.namedParamValues [i];
433 if (name == "CallingConvention")
434 native_cc = (CallingConvention)value;
435 else if (name == "CharSet")
436 charset = (CharSet)value;
437 else if (name == "EntryPoint")
438 pi_entry = (string)value;
439 else if (name == "ExactSpelling")
440 ExactSpelling = (bool)value;
441 else if (name == "SetLastError")
442 SetLastError = (bool)value;
443 else if (name == "PreserveSig")
444 preserveSig = (bool)value;
445 else if (name == "BestFitMapping")
446 BestFitMapping = (bool)value;
447 else if (name == "ThrowOnUnmappableChar")
448 ThrowOnUnmappableChar = (bool)value;
451 attrs |= MethodAttributes.PinvokeImpl;
453 iattrs |= MethodImplAttributes.PreserveSig;
456 case "System.Runtime.InteropServices.PreserveSigAttribute":
457 iattrs |= MethodImplAttributes.PreserveSig;
459 case "System.Runtime.CompilerServices.SpecialNameAttribute":
460 attrs |= MethodAttributes.SpecialName;
462 case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
463 attrs |= MethodAttributes.HasSecurity;
467 if (cattrs != null) {
468 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
469 cattrs.CopyTo (new_array, 0);
470 new_array [cattrs.Length] = customBuilder;
473 cattrs = new CustomAttributeBuilder [1];
474 cattrs [0] = customBuilder;
479 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
482 throw new ArgumentNullException ("con");
483 if (binaryAttribute == null)
484 throw new ArgumentNullException ("binaryAttribute");
485 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
488 public void SetImplementationFlags (MethodImplAttributes attributes)
494 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
498 throw new ArgumentNullException ("pset");
499 if ((action == SecurityAction.RequestMinimum) ||
500 (action == SecurityAction.RequestOptional) ||
501 (action == SecurityAction.RequestRefuse))
502 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
506 if (permissions != null) {
507 /* Check duplicate actions */
508 foreach (RefEmitPermissionSet set in permissions)
509 if (set.action == action)
510 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
512 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
513 permissions.CopyTo (new_array, 0);
514 permissions = new_array;
517 permissions = new RefEmitPermissionSet [1];
519 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
520 attrs |= MethodAttributes.HasSecurity;
524 [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
525 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
528 throw new NotImplementedException ();
532 public void SetSymCustomAttribute (string name, byte[] data)
535 throw new NotImplementedException ();
538 public override string ToString()
540 return "MethodBuilder [" + type.Name + "::" + name + "]";
544 public override bool Equals (object obj)
546 return base.Equals (obj);
549 public override int GetHashCode ()
551 return name.GetHashCode ();
554 internal override int get_next_table_index (object obj, int table, bool inc)
556 return type.get_next_table_index (obj, table, inc);
559 void ExtendArray<T> (ref T[] array, T elem) {
563 var newa = new T [array.Length + 1];
564 Array.Copy (array, newa, array.Length);
567 array [array.Length - 1] = elem;
570 internal void set_override (MethodInfo mdecl)
572 ExtendArray<MethodInfo> (ref override_methods, mdecl);
575 private void RejectIfCreated ()
578 throw new InvalidOperationException ("Type definition of the method is complete.");
581 private Exception NotSupported ()
583 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
586 public override MethodInfo MakeGenericMethod (params Type [] typeArguments)
588 if (!IsGenericMethodDefinition)
589 throw new InvalidOperationException ("Method is not a generic method definition");
590 if (typeArguments == null)
591 throw new ArgumentNullException ("typeArguments");
592 if (generic_params.Length != typeArguments.Length)
593 throw new ArgumentException ("Incorrect length", "typeArguments");
594 foreach (Type type in typeArguments) {
596 throw new ArgumentNullException ("typeArguments");
599 return new MethodOnTypeBuilderInst (this, typeArguments);
602 public override bool IsGenericMethodDefinition {
604 return generic_params != null;
608 public override bool IsGenericMethod {
610 return generic_params != null;
614 public override MethodInfo GetGenericMethodDefinition ()
616 if (!IsGenericMethodDefinition)
617 throw new InvalidOperationException ();
622 public override Type[] GetGenericArguments ()
624 if (generic_params == null)
627 Type[] result = new Type [generic_params.Length];
628 for (int i = 0; i < generic_params.Length; i++)
629 result [i] = generic_params [i];
634 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
637 throw new ArgumentNullException ("names");
638 if (names.Length == 0)
639 throw new ArgumentException ("names");
641 generic_params = new GenericTypeParameterBuilder [names.Length];
642 for (int i = 0; i < names.Length; i++) {
643 string item = names [i];
645 throw new ArgumentNullException ("names");
646 generic_params [i] = new GenericTypeParameterBuilder (type, this, item, i);
649 return generic_params;
652 public void SetReturnType (Type returnType)
657 public void SetParameters (params Type[] parameterTypes)
659 if (parameterTypes != null) {
660 for (int i = 0; i < parameterTypes.Length; ++i)
661 if (parameterTypes [i] == null)
662 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
664 this.parameters = new Type [parameterTypes.Length];
665 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
669 public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
671 SetReturnType (returnType);
672 SetParameters (parameterTypes);
673 this.returnModReq = returnTypeRequiredCustomModifiers;
674 this.returnModOpt = returnTypeOptionalCustomModifiers;
675 this.paramModReq = parameterTypeRequiredCustomModifiers;
676 this.paramModOpt = parameterTypeOptionalCustomModifiers;
679 public override Module Module {
685 void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
687 throw new NotImplementedException ();
690 void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
692 throw new NotImplementedException ();
695 void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
697 throw new NotImplementedException ();
700 void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
702 throw new NotImplementedException ();
705 public override ParameterInfo ReturnParameter {
706 get { return base.ReturnParameter; }